Search code examples
javafreemarker

How to round decimal number to two decimal places?


I have Decimal numbers and I would like to round them to two decimal places. So for example:

2222.333333 -> 2222.33

51.22 -> 51.22

27.0012 -> 27.00

37.28945 -> 37.29

7891.1 -> 7891.10

Could you tell me how to do this? I have these numbers parsed from xml so all these numbers are strings. I tried to parsing it first to number within ?number and do somethnig like this:

<#return value?number?string('0.##')/>

but I'm not sure what should I put into () of ?string so it could be applied to all these cases.


Solution

  • You can use:

    <#return value?number?string('0.00')/>
    

    The pattern format is the same as in DecimalFormat.