views:

2544

answers:

4

Hello all,

I have this line of code which rounds my numbers to 2 decimal places. But the thing is I get numbers like this. 10.8, 2.4 etc. These are not my idea of 2 decimal places so how I can improve this:

Math.round(price*Math.pow(10,2))/Math.pow(10,2);

I want numbers like 10.80, 2.40 etc. Use of JQuery is fine with me.

Thanks for any help.

+1  A: 

Maybe you want to include a sprintf library for JavaScript.

Thilo
A: 

Try using sprintf() function from PHP.js to call something like:

var value = sprintf("%01.2f", inputvalue);
Lukman
I tried this first and it worked for me - thank you!
Abs
+15  A: 

To format a number using fixed-point notation, you can simply use the toFixed method:

(10.8).toFixed(2); // 10.80

var num = 2.4;
alert(num.toFixed(2)); // 2.40
CMS
A: 
result = parseFloat(92.28941667);
desiredDecPlaces = parseInt(2);
actualDecPlaces = parseInt(8);

for (i=actualDecPlaces-1;i>=desiredDecPlaces;i--)
{
    tmp5 = '1';
    for (j=1;j<=i;j++) {tmp5 = tmp5 + '0';}
    power = parseInt(tmp5);
    result = Math.round(result*power)/power
    alert(result);
}
CoolScript