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

后端 未结 6 2043
醉酒成梦
醉酒成梦 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条回答
  •  天涯浪人
    2020-12-30 20:57

    Use toPrecision :)

    var y = 67537653.76828732668326;
    y = (String(y).indexOf('.') !== -1) ? +y.toPrecision(String(y).indexOf('.') + 2) : +y.toFixed(2);
    // => 67537653.76
    

    The 2 in the second line dictates the number of decimal places, this approach returns a number, if you want a string remove the "+" operator.

提交回复
热议问题