Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding a number to exactly two decimal places for currency formatting

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?

like image 897
user1667474 Avatar asked Sep 13 '12 08:09

user1667474


People also ask

How can I format a decimal to always show 2 decimal places?

1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number is round to 2 decimal places.

What is the number 2.738 correct to 2 decimal places?

74, which is 2 decimal places.


4 Answers

I am using this, seems to be ok

Math.round(x * 100)/100

Its look like shortest

like image 89
user1921553 Avatar answered Oct 09 '22 09:10

user1921553


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

.toFixed(2)
like image 26
Vytalyi Avatar answered Oct 09 '22 20:10

Vytalyi


(Math.round(num*Math.pow(10,2))/Math.pow(10,2)).toFixed(2)
like image 10
xdazz Avatar answered Oct 09 '22 20:10

xdazz


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);
}
like image 1
Miguel Avatar answered Oct 09 '22 21:10

Miguel