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

后端 未结 6 2042
醉酒成梦
醉酒成梦 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 21:01

    As T.J answered, the toFixed method will do the appropriate rounding if necessary. It will also add trailing zeroes, which is not always ideal.

    (4.55555).toFixed(2);
    //-> "4.56"
    
    (4).toFixed(2);
    //-> "4.00"
    

    If you cast the return value to a number, those trailing zeroes will be dropped. This is a simpler approach than doing your own rounding or truncation math.

    +parseFloat((4.55555).toFixed(2));
    //-> 4.56
    
    +parseFloat((4).toFixed(2));
    //-> 4
    

提交回复
热议问题