views:

56

answers:

3

Hello , I am looking for an efficient way to cut floating number at Javascript which are long. I need this because my output for taking percentage of two numbers can be sometimes like 99.4444444 while I am only interested in the first 2 digits after "." such as 99.44

My current percentage taking function for 2 numbers:

function takePercentage(x,y){
     return (x /y) * 100;
}
+3  A: 

You can use number.toFixed:

function takePercentage(x,y){
     return ((x /y) * 100).toFixed(2);
}
CMS
Note that toFixed fails to round numbers in IE, which can combine with floating-point inaccuracies to give unexpected results.
bobince
+2  A: 
function takePercentage(x,y){
     n = (x /y) * 100;
     return n.toPrecision(2);
}

That should do it!

inkedmn
this isn't correct . 99.345.toPrecision(2) for example yields "99"
Scott Evernden
toPresicion returns the number rounded to a precision of **significant digits**, i.e.: `123.456.toPrecision(3) == 123;`, `123.456.toPrecision(2) == 120;`, `123.456.toPrecision(4) == 123.5;` more info here: http://is.gd/3zchw, you should also use the `var` statement to declare `n`, if you don't n is declared globally
CMS
+1  A: 

How about this:

Math.round( myfloatvalue*100 ) / 100
cg
this works with google visualisation api table generation while "toFixed(2)" somehow doesn't.
Hellnar