I have no idea how to do this? I'm adding comma numbers, result is of course always a number with way too many digits after the comma. anyone?
This question is related to
javascript
math
rounding
This is not really CPU friendly, but :
Math.round(number*100)/100
works as expected.
Previous answers forgot to type the output as an Number again. There is several ways to do this, depending on your tastes.
+my_float.toFixed(2)
Number(my_float.toFixed(2))
parseFloat(my_float.toFixed(2))
This worked for me:
var new_number = float.toFixed(2);
Example:
var my_float = 0.6666
my_float.toFixed(3) # => 0.667
Though we have many answers here with plenty of useful suggestions, each of them still misses some steps.
So here is a complete solution wrapped into small function:
function roundToTwoDigitsAfterComma(floatNumber) {
return parseFloat((Math.round(floatNumber * 100) / 100).toFixed(2));
}
Just in case you are interested how this works:
toFixed(2)
to keep 2 digits after
comma and throw other unuseful partparseFloat()
function as
toFixed(2)
returns string insteadNote: If you keep last 2 digits after comma because of working with monetary values, and doing financial calculations keep in mind that it's not a good idea and you'd better use integer values instead.
I use this:
function round(value, precision) {_x000D_
_x000D_
if(precision == 0)_x000D_
return Math.round(value); _x000D_
_x000D_
exp = 1;_x000D_
for(i=0;i<precision;i++)_x000D_
exp *= 10;_x000D_
_x000D_
return Math.round(value*exp)/exp;_x000D_
}
_x000D_
use the below code.
alert(+(Math.round(number + "e+2") + "e-2"));
UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.
toFixed()
- method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.Math.round(n)
- rounds a number to the nearest integer. Thus turning:0.5 -> 1; 0.05 -> 0
so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):
0.55555 * 100
= 55.555 Math.Round(55.555)
-> 56.00056.000 / 100
= 0.56000 (0.56000).toFixed(2)
-> 0.56and this is the code:
(Math.round(number * 100)/100).toFixed(2);
Source: Stackoverflow.com