Round half pennies up?
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
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;
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.45
// round "original" to 1 decimal
var result = Math.round(original*10)/10;
// returns 28.5
// round 8.111111 to 3 decimals
var result = Math.round(8.111111*1000)/1000;
// returns 8.111