Click to See Complete Forum and Search --> : Javascript: parseFloat(): Rounding


sk24
02-10-2003, 01:25 PM
Hi!
How would I restrict Javascript to only 2 digits after decimal point.
e.g.
alert( "2544.56 + 1991 + 480 = " + 2544.56 + 1991 + 480 ) ;

The above line gives me result : 2544.561991480

How would I get only : 2544.56

I tried parseFloat(), eval().

Thanks,

Nevermore
02-10-2003, 01:54 PM
For a start, you are using strings, so javascript is just putting them together, not adding them. You need to create them using the float command, or if you are getting them from somewhere, process them with parsefloat(). Then, to round to two decimal places, use the following code: (assumes the total of all your numbers is a floating point number called
num.


Math.round(num * 100) / 100;

Dan Drillich
02-10-2003, 06:33 PM
Please look at -
http://forums.webdeveloper.com/showthread.php?s=&threadid=3591&highlight=toFixed

Please try -


alert( "2544.56 + 1991 + 480 = " + (2544.56 + 1991 + 480).toFixed(2) ) ;


Cheers,
Dan