Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round half pennies up? [duplicate]

Tags:

javascript

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)

like image 371
mpen Avatar asked Aug 31 '10 04:08

mpen


People also ask

How do you round off decimals?

There are certain rules to follow when rounding a decimal number. Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up.

How do you round to the nearest tenth?

To round the decimal number to its nearest tenth, look at the hundredth number. If that number is greater than 5, add 1 to the tenth value. If it is less than 5, leave the tenth place value as it is, and remove all the numbers present after the tenth's place.

How do you round to the nearest one?

To round to nearest one, ten, hundred, thousand and so on: if the rounding digit is 0, 1, 2, 3, or 4, change all digits to the right of it to zeroes. if the rounding digit is 5, 6, 7, 8, or 9, add one to the rounding digit and change all digits to the right of it to zeroes.


1 Answers

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
like image 110
zneak Avatar answered Oct 21 '22 05:10

zneak