Round half a penny?

Possible duplicates:
round to the nearest 0.10
round JavaScript number up to N decimal places

How can I combine floats like 0.075 to 0.08 in Javascript?

+7
javascript
source share
4 answers

You need to multiply by a hundred (so that the cents are rounded), round up, and then divide by one hundred to get the correct dollar price 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 0.08 dollars in the end 
+7
source share

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) and ceil (rounds). Unfortunately, all three are only rounded to the nearest integer. However, you can first multiply the amount of your dollar (get a penny), and then use ceil to round to the next penny;

 var money = 0.075; var pennies = money * 100; money = Math.ceil(pennies) / 100; 
+4
source share

Use Math.Round. Adapted 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 
+2
source share
 alert(0.755.toFixed(2)); 
+1
source share

All Articles