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?
1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number is round to 2 decimal places.
74, which is 2 decimal places.
I am using this, seems to be ok
Math.round(x * 100)/100
Its look like shortest
You can add this to number which you want to set specific format
.toFixed(2)
(Math.round(num*Math.pow(10,2))/Math.pow(10,2)).toFixed(2)
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With