簡體   English   中英

如何在Thymeleaf模板中僅在必要時控制有效數字?

[英]How to control significant digits, ONLY when necessary, in a Thymeleaf template?

使用th:text屬性評估和呈現數字字段時,Thymeleaf顯示可用的完整位數。 例如,這個:

<span th:text="${user.averageScore}"/>

...可能會在瀏覽器屏幕上呈現:

107.54896

我想將這個金額四舍五入到不超過兩位小數。 從Thymeleaf文檔中可以看出:

<span th:text="${#numbers.formatDecimal(user.averageScore, 0, 2)}"/>

...將輸出更改為:

107.55

但是,有沒有辦法使這個更靈活......如果值的FEWER小於兩位小數? 我只想刪除小數位,以減少兩個。 我從不想添加小數位,最多可以達到兩位。 如果上面的字段的值為107,那么它將呈現為:

107.00

如何將Thymeleaf格式數字制作為小數點后兩位或更少...而不是僅僅兩位小數,無論如何?

嗨,你可以嘗試這樣的事情。

<span th:text="${user.averageScore} % 1 == 0? ${user.averageScore} :${#numbers.formatDecimal(user.averageScore, 0, 2)}"/>

在Thymeleaf 2.1中沒有簡單的方法可以做到這一點,但有兩種困難的方法。

困難的方法#1:Fork Thymeleaf並為類org.thymeleaf.expression.Numbers添加一個格式方法,它可以做你想要的(添加一個采用DecimalFormat模式的方法看起來像是一個邏輯擴展)

艱難的方法#2:為Thymeleaf添加一個方言,它提供了一個新的表達式類,可以進行你想要的格式化。 我的下面的例子是基於使用Spring和Thymeleaf來注冊方言來格式化代表小時的數字。

第1步:注冊方言:

@Component
public class ThymeLeafSetup implements InitializingBean {

@Autowired
private SpringTemplateEngine templateEngine;

@Override
public void afterPropertiesSet() throws Exception {
    templateEngine.addDialect(new HoursDialect());
}
}

步驟#2:創建方言類(委托給TimeUtils靜態方法的格式化邏輯) - 基於Java8TimeDialect:

public class HoursDialect extends AbstractDialect implements IExpressionEnhancingDialect {
public static class Hours {
    public String format(BigDecimal hours) {
        return TimeUtils.formatHours(hours);
    }
}

@Override
public String getPrefix() {
    // No attribute or tag processors, so we don't need a prefix at all and
    // we can return whichever value.
    return "hours";
}

@Override
public boolean isLenient() {
    return false;
}

@Override
public Map<String, Object> getAdditionalExpressionObjects(IProcessingContext processingContext) {
    return Collections.singletonMap("hours", new Hours());
}
}

步驟#3:基於DecimalFormat創建格式化邏輯

public class TimeUtils {

public static String formatHours(BigDecimal hours) {
    DecimalFormat format = new DecimalFormat("#0.##");
    format.setGroupingUsed(true);
    format.setGroupingSize(3);
    return format.format(hours);
}
}

步驟#4:格式化邏輯的測試

@Test
public void formatDecimalWilLFormatAsExpected() {
    verifyHourNumberFormatsAsExpected("1.5", "1.5");
    verifyHourNumberFormatsAsExpected("1.25", "1.25");
    verifyHourNumberFormatsAsExpected("123.0", "123");
    verifyHourNumberFormatsAsExpected("1230", "1,230");
}

void verifyHourNumberFormatsAsExpected(String number, String expected) {
    assertThat(TimeUtils.formatHours(new BigDecimal(number))).isEqualTo(expected);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM