Home > Software engineering >  How to round decimal number to two decimal places?
How to round decimal number to two decimal places?

Time:10-27

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.

CodePudding user response:

You can use:

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

The pattern format is the same as in DecimalFormat.

CodePudding user response:

If you are using Javascript, you could do something like this: -

let number = 5.56789;
let decimalPlaces = 2 // Number of decimal places
console.log(number.toFixed(decimalPlaces));
// Console logs "5.56". If decimalPlaces is 3, it would print "5.567"
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related