tags:

views:

88

answers:

4

Possible Duplicates:
round up nearest 0.10
round number in JavaScript to N decimal places

How can I round floats such as 0.075 up to 0.08 in Javascript?

+2  A: 

You need to multiply by a hundred (so that the cents are what will get rounded), round, then divide by a hundred to get the right price in dollars again.

var dollars = 0.075; // 0.075 dollars
var cents = dollars * 100; // ... is 7.5 cents
var roundedCents = Math.round(cents); // ... but should really be 8 cents
var roundedPrice = roundedCents / 100; // ... so it's 0.08 dollars in the end
zneak
A: 

Use Math.Round. Taken from this article

var original=28.4531) //round "original" to two decimals
var result=Math.round(original*100)/100  //returns 28.452) // round "original" to 1 decimal
var result=Math.round(original*10)/10  //returns 28.53) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000  //returns 8.111
Dave Barker
+1  A: 

Javascript has three rounding functions, all of which are members of the Math object: round (rounds up or down, to the nearest integer), floor (rounds down) and ceil (rounds up). Unfortunately, all three only round to the nearest whole number. However, you can multiply your dollar amount first (to get pennies) and then use ceil to round up to the next penny;

var money = 0.075;
var pennies = money * 100;
money = Math.ceil(pennies) / 100;
Daniel Vandersluis
Should be `Math.round` but the idea is the same. Thanks!
Mark
@Mark Your question asked for rounding up... ;)
Daniel Vandersluis
A: 
alert(0.755.toFixed(2));
epascarello
`0.075.toFixed(2)` is `0.07`, not `0.08` as requested.
Daniel Vandersluis
Okay that is messed up. I mistyped my test code with an extra 5 with FF 3.5.11 javascript:alert( (0.075.toFixed(2)) + "\n" + (0.0755.toFixed(2)) ); Scratching my head on this one. lol
epascarello
Very strange http://jsbin.com/uyiho3 Need to see what the spec says. :)
epascarello
toFixed bugs in bugzilla https://bugzilla.mozilla.org/show_bug.cgi?id=496540 and https://bugzilla.mozilla.org/show_bug.cgi?id=588767 man is that inconsistent. lol
epascarello