Anyone knows such a function in javascript?
+6
A:
num = 30.006649999999994;
result = num.toFixed(2); // result will equal 30.01
Here's a sample of this code over at JSBin
p.campbell
2010-10-15 14:14:52
-1 Why the up-votes? toFixed() returns a string.
Ivo Wetzel
2010-10-15 14:20:33
Unfortunately, `toFixed()` is crazy broken in IE. eg. `(1.9).toFixed(0)` is `2`, but `(0.9).toFixed(0)` is `0`
bobince
2010-10-15 15:00:43
@Ivo: thanks for the downvote! The answer was solely to illustrate to the questioner how to perform the **rounding** being sought. I hadn't claimed it'd return a numeric value. Perhaps you'd like to go downvote the other `.toFixed` solutions. That'll make yourself feel better about nitpicking answers on StackOverflow. Have A Nice Day!
p.campbell
2010-10-15 15:01:00
I'm not nitpicking here, it's just that the opener does not seem to have much clue about what he is doing. So not telling him that it will return a string, will just make him wonder why `result + 2` doesn't work the way he expected it to.
Ivo Wetzel
2010-10-15 15:07:15
+5
A:
Just choose your desired accuracy and use a multiplication/division together with round
function.
In your case, if you want to round to second decimal digit you could do
Math.round(value*100)/100
Jack
2010-10-15 14:16:25
This can fail for large values where the `*100` causes precision to be lost. eg. `Math.round(100000000000000.33*100)/100` returns `100000000000000.31` despite `.33` being representable as a float.
bobince
2010-10-15 15:14:54
A:
Use Number.toFixed(digitsAfterPoint).
See description here.
Eugene Mayevski 'EldoS Corp
2010-10-15 14:16:55
+1
A:
I always use my own round function for that.
function round(value, precision){
if(precision){
var exponent = Math.pow(10, precision);
return Math.round(value * exponent)/exponent;
}else{
return Math.round(value);
}
}
You can call it like this:
round(30.006649999999994, 2);
WoLpH
2010-10-15 14:17:54
A:
Rated up the answer by p.campbell, it doesn't look like I can comment on someone's answer yet.
But all you need to make that a number is add parseFloat();
num = 30.006649999999994; result = parseFloat(num.toFixed(2)); // result will equal 30.01
Darye
2010-10-15 14:49:51
Is it any shorter? No. Does it still invoke unnecessary type conversion? Yes.
Ivo Wetzel
2010-10-15 15:04:34