I am stuck with formatting the currency in HTML 5. I have application where I have to format the currency. I have below code snippet
<td class="right"><span th:inline="text">$ [[${abc.value}]]</span></td>
Where from DAO abc I am reading the currency value, it should be formatted. Currently printing $ 1200000.0 it should print $ 1,200,000.0 .0
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.
来源:https://stackoverflow.com/questions/14160304/how-to-format-the-currency-in-html5-with-thymeleaf