Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round to 2 decimal places?

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

I'm using this to get the number:

Math.floor(iAlt / 50) * 50;

How can i get the 0 behind the ,5?

like image 561
Patrick R Avatar asked Nov 22 '11 10:11

Patrick R


1 Answers

Try the toFixed() method, which pads the decimal value to length n with 0's.

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

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

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

like image 86
Matt Avatar answered Sep 23 '22 18:09

Matt