简体   繁体   English

如何在Thymeleaf模板中仅在必要时控制有效数字?

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

When using the th:text attribute to evaluate and render a numeric field, Thymeleaf displays the full number of digits available. 使用th:text属性评估和呈现数字字段时,Thymeleaf显示可用的完整位数。 For example, this: 例如,这个:

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

... might render on the browser screen: ...可能会在浏览器屏幕上呈现:

107.54896

I would like to display this amount rounded to no more than two decimal places. 我想将这个金额四舍五入到不超过两位小数。 From the Thymeleaf documentation, this: 从Thymeleaf文档中可以看出:

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

... changes the output to this: ...将输出更改为:

107.55

However, is there a way to make this more flexible... in cases where the value has FEWER than than two decimal places? 但是,有没有办法使这个更灵活......如果值的FEWER小于两位小数? I only want to remove decimal places, to get down to two. 我只想删除小数位,以减少两个。 I never want to ADD decimal places, to get up to two. 我从不想添加小数位,最多可以达到两位。 If the field above has a value of 107, then it would render as: 如果上面的字段的值为107,那么它将呈现为:

107.00

How can I make Thymeleaf format numbers for two decimal places, or less... rather than just two decimal places, no matter what? 如何将Thymeleaf格式数字制作为小数点后两位或更少...而不是仅仅两位小数,无论如何?

嗨,你可以尝试这样的事情。

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

There's no easy way to do this in Thymeleaf 2.1, but there are two hard ways. 在Thymeleaf 2.1中没有简单的方法可以做到这一点,但有两种困难的方法。

Hard way #1: Fork Thymeleaf and add a format method to class org.thymeleaf.expression.Numbers that does what you want (adding a method that takes a DecimalFormat pattern would seem like a logical extension) 困难的方法#1:Fork Thymeleaf并为类org.thymeleaf.expression.Numbers添加一个格式方法,它可以做你想要的(添加一个采用DecimalFormat模式的方法看起来像是一个逻辑扩展)

Hard way #2: Add a dialect to Thymeleaf that provides a new expression class that does the formatting you want. 艰难的方法#2:为Thymeleaf添加一个方言,它提供了一个新的表达式类,可以进行你想要的格式化。 My example below is based on using Spring with Thymeleaf to register a dialect to format numbers representing hours. 我的下面的例子是基于使用Spring和Thymeleaf来注册方言来格式化代表小时的数字。

Step 1: Register the dialect: 第1步:注册方言:

@Component
public class ThymeLeafSetup implements InitializingBean {

@Autowired
private SpringTemplateEngine templateEngine;

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

Step #2: Create the dialect class (formatting logic delegated to TimeUtils static method) - based on Java8TimeDialect: 步骤#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());
}
}

Step #3: Create formatting logic based on DecimalFormat 步骤#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);
}
}

Step #4: Tests of formatting logic 步骤#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