Rounding a number to exactly two decimal places for currency formatting
Asked Answered
F

4

14

I need to round to two decimal places for currency.

Both

Math.round(num*Math.pow(10,2))/Math.pow(10,2)

and

Math.round(num*Math.pow(10,2))/Math.pow(10,2)

work except it cuts any trailing zero's off so I get 29.9 instead of 29.90.

What is the best way around this?

Farrell answered 13/9, 2012 at 8:28 Comment(1)
possible duplicate of Format number to always show 2 decimal placesMarje
R
29

You can add this to number which you want to set specific format

.toFixed(2)
Robbirobbia answered 13/9, 2012 at 8:30 Comment(5)
toFixed(2) is not good for currency formatting since it sometimes rounds half up and sometimes half down. For example (0.615).toFixed(2) gives 0.61 (half down) while (0.625) gives 0.63 (half up).Fronniah
For currency, Vytalyi's answer doesn't work property, to the examples that Luksaz stated.Greybeard
@Robbirobbia answer is absolutely fine. .toFixed follows rounding principles as stated in Mathematics and as it should. If an odd number prefixes the number 5 then truncation happens else it rounds up.Hanseatic
Yikes, (0.615).toFixed(2) is a weird wrong with returning 0.61 case. While (0.515).toFixed(2) works fine with returning the correct 0.52.Erbium
@kaiser, it uses banker's rounding: en.wikipedia.org/wiki/Rounding#Round_half_to_evenSaltigrade
G
10
(Math.round(num*Math.pow(10,2))/Math.pow(10,2)).toFixed(2)
Gasconade answered 13/9, 2012 at 8:31 Comment(1)
Actually (Math.round(0.22499999999999998*Math.pow(10,2))/Math.pow(10,2)).toFixed(2) returns 0.22 while it should be 0.23Finnigan
W
3

I am using this, seems to be ok

Math.round(x * 100)/100

Its look like shortest

Woolsack answered 14/5, 2021 at 8:34 Comment(0)
V
1

It makes sense to think about it as a total amount of cents. 19.999 = 1999.9 cents, the 3rd decimal does not matter you cant pay it anyway.

This makes sense:

function convertToMoney(val){
    return (Math.floor(val*100).toFixed(0)/100).toFixed(2);
}
Vaasta answered 30/4, 2021 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.