How to customize number format in freemarker?

时光总嘲笑我的痴心妄想 提交于 2019-12-01 06:31:23

You can also try ?string(",##0.00"). However in this case you need to explicitly add $ and - sign would be after $ in case of negative numbers.

<#local total = 3343434/>
$ ${total?string(",##0.00")}  //$ 3,343,434.00

<#local total = -3343434/>
$ ${total?string(",##0.00")}  //$ -3,343,434.00

OR in case if you want what was expected you can replace the strings.

<#local total = -3343434/>
<#local total = "$ " + total?string(",##0.00")/>

${total?replace('$ -','- $')}   //- $3,343,434.00

Update: Since FreeMarker 2.3.24 you can define named custom number formats, which can be an alias to a number format pattern (or even a formatter implemented in Java, but that level of flexibility isn't needed in this case). So add a custom number format called "money" as an alias to "¤,##0.00" to the FreeMarker configuration, and then you can write something like ${total?string.@money}. See: http://freemarker.org/docs/pgui_config_custom_formats.html

Currently FreeMarker just uses the formatting facility of the Java platform, so it's only as configurable as that (assuming you want to use ?string and ?string.somethingPredefiendHere). Which is not much... but, in general, the formatting categories provided by the Java platform is not fine-gradient enough anyway, I mean, you don't have application-domain categories like, price-of-product, a salary, a price on the stock, etc. (This demand is more frequent with non-currency numbers though.) So I think, generally, you want to make a formatter function, that you can use like ${salary(someNumber)}, ${price(someNumber)}, etc. Those functions can be implemented in a commonly #included/#imported template like a #function or in Java by using #assign salary = 'com.example.SalarayMethod'?new() in place of #function, where com.example.SalarayMethod is a TemplateMethodModelEx.

How about taking a mod of your number, convert it to the required string format and finally add a '-' prefix to the final string. You can retain the default format in just two steps.

Joshua Moore

Freemarker uses the currency formatting provided by the Java platform.

It requires a little tweaking of the DecimalFormat returned by NumberFormat.getCurrencyInstance() (which is what is called when you call .currency). You can see examples of it here.

However, that said it will likely be more effective for you to create a macro in freemarker to call which will handle your specific formatting.

Sorry for not having an example of what that macro would look like, but it's a good starter into macros in freemarker since you are just learning.

You might investigate if you can supply a custom format using the exposed configuration for number formats that will meet your needs.

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