Search code examples
javascriptfloating-pointdecimallimit

Limit the amount of number shown after a decimal place in javascript


Hay, i have some floats like these

4.3455
2.768
3.67

and i want to display them like this

4.34
2.76
3.67

I don't want to round the number up or down, just limit the amount of numbers shown after the decimal place to 2.


Solution

  • You're looking for toFixed:

    var x = 4.3455;
    alert(x.toFixed(2)); // alerts 4.35 -- not what you wanted!
    

    ...but it looks like you want to truncate rather than rounding, so:

    var x = 4.3455;
    x = Math.floor(x * 100) / 100;
    alert(x.toFixed(2)); // alerts 4.34