Format number to always show 2 decimal places

前端 未结 30 2847
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 08:17

I would like to format my numbers to always display 2 decimal places, rounding where applicable.

Examples:

number     display
------     -------
1            


        
30条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 08:32

    var num = new Number(14.12);
    console.log(num.toPrecision(2));//outputs 14
    console.log(num.toPrecision(3));//outputs 14.1
    console.log(num.toPrecision(4));//outputs 14.12
    console.log(num.toPrecision(5));//outputs 14.120
    

提交回复
热议问题