Mei Mei - 2 months ago 17
HTML Question

How to customize number format in freemarker?

I am using freemarker and trying to display numbers in this format:

for example. This was easily taken care of by using
(assuming "total" is some number).

However, when I have negative numbers, it's showing them like this:
instead of this:
. I need the negative sign instead of the parenthesis. Is there a way I could customize the formatting so it does everything that the
did but replace the negative value behavior? I am relatively new to freemarker, so detailed responses are appreciated!


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:

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.