views:

155

answers:

6

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
-1 Why the up-votes? toFixed() returns a string.
Ivo Wetzel
Unfortunately, `toFixed()` is crazy broken in IE. eg. `(1.9).toFixed(0)` is `2`, but `(0.9).toFixed(0)` is `0`
bobince
@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
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
+1  A: 
num = 30.006649999999994;
num2 = num.toFixed(2);
Rocket
+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
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
A: 

Use Number.toFixed(digitsAfterPoint).

See description here.

Eugene Mayevski 'EldoS Corp
+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
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
Is it any shorter? No. Does it still invoke unnecessary type conversion? Yes.
Ivo Wetzel