There is no easy way to do this in Thymeleaf 2.1, but there are two difficult ways.
Hard way # 1: Fork Thymeleaf and add a format method to the org.thymeleaf.expression.Numbers class that does what you want (adding a method that accepts a DecimalFormat template will look like a logical extension)
Hard Way # 2: Add a dialect to Thymeleaf, which provides a new expression class that does the formatting you need. My example below is based on using Spring with Thymeleaf to register a dialect to format numbers representing a clock.
Step 1: Register the dialect:
@Component public class ThymeLeafSetup implements InitializingBean { @Autowired private SpringTemplateEngine templateEngine; @Override public void afterPropertiesSet() throws Exception { templateEngine.addDialect(new HoursDialect()); } }
Step # 2: Create a dialect class (formatting logic delegated to the static TimeUtils method) - based on 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() {
Step # 3: Create Formatting Logic Based on 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: formatting logic tests
@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); }
source share