Patrick R
Patrick R

Reputation: 1979

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?

Upvotes: 12

Views: 23646

Answers (1)

Matt
Matt

Reputation: 75307

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).

Upvotes: 30

Related Questions