开发者

Round half pennies up? [duplicate]

This question already has answers here: Closed 12 years ago.

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? (开发者_开发技巧below half should run down)


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


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


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;


alert(0.755.toFixed(2));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜