How to format the currency in HTML5 with thymeleaf

空扰寡人 提交于 2020-01-09 09:33:01

问题


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


回答1:


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>



回答2:


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')}



回答3:


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>




回答4:


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

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