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

后端 未结 6 2046
醉酒成梦
醉酒成梦 2020-12-30 20:35

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

6条回答
  •  旧时难觅i
    2020-12-30 20:47

    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
    

提交回复
热议问题