How to round to two decimal places?

I have a comma number, for example: 254,5 . I need 0 behind ,5 , so it stands instead of 254,50 .

I use this to get the number:

 Math.floor(iAlt / 50) * 50; 

How can I get 0 for ,5 ?

+8
javascript math
source share
1 answer

Try the toFixed() method, which imposes a decimal value on a length n 0.

 var result = (Math.floor(iAlt / 50) * 50).toFixed(2); 

A Number will always remove trailing zeros, so toFixed returns String .

It is important to note that toFixed must be called on a number. Call parseFloat() or parseInt() to convert the string to a number first if necessary (not in this situation, but for future reference).

+24
source share

All Articles