How to format the currency in HTML5 with thymeleaf

人盡茶涼 提交于 2019-11-28 21:08:38

You can use the #numbers utility object, which methods you can see here: http://www.thymeleaf.org/apidocs/thymeleaf/2.0.15/org/thymeleaf/expression/Numbers.html

For example:

<span th:inline="text">$ [[${#numbers.formatDecimal(abc.value, 0, 'COMMA', 2, 'POINT')}]]</span>

Nevertheless, you can also do this without inlining (which is the thymeleaf recommended way):

<td>$ <span th:text="${#numbers.formatDecimal(abc.value, 0, 'COMMA', 2, 'POINT')}">10.00</span></td>

I recommend to use the DEFAULT value (= based on locale) in case your application has to deal with different languages :

${#numbers.formatDecimal(abc.value, 1, 'DEFAULT', 2, 'DEFAULT')}

From Thymeleaf doc (more precisely NumberPointType) :

/* 
 * Set minimum integer digits and thousands separator: 
 * 'POINT', 'COMMA', 'NONE' or 'DEFAULT' (by locale).
 * Also works with arrays, lists or sets
 */
${#numbers.formatInteger(num,3,'POINT')}
${#numbers.arrayFormatInteger(numArray,3,'POINT')}
${#numbers.listFormatInteger(numList,3,'POINT')}
${#numbers.setFormatInteger(numSet,3,'POINT')}

/*
 * Set minimum integer digits and (exact) decimal digits, and also decimal separator.
 * Also works with arrays, lists or sets
 */
${#numbers.formatDecimal(num,3,2,'COMMA')}
${#numbers.arrayFormatDecimal(numArray,3,2,'COMMA')}
${#numbers.listFormatDecimal(numList,3,2,'COMMA')}
${#numbers.setFormatDecimal(numSet,3,2,'COMMA')}

You can now more simply call the formatCurrency method in the numbers utility:

#numbers.formatCurrency(abc.value)

This will remove the need for a currency symbol as well.

Example: <span th:remove="tag" th:text="${#numbers.formatCurrency(abc.value)}">$100</span>

You'd inline using Thymeleaf's numbers utility object as follows:

<span>[[${#numbers.formatCurrency(abc.value)}]]</span>

In the view, it'll even prepend the dollar sign ($) for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!