javahtmlfreemarkernumber-formatting

How to customize number format in freemarker?


I am using freemarker and trying to display numbers in this format: $3,343,434.00 for example. This was easily taken care of by using ${total?string.currency} (assuming "total" is some number).

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


Solution

  • 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