Format number to always show 2 decimal places

前端 未结 30 3396
爱一瞬间的悲伤
爱一瞬间的悲伤 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:26

    I do like:

    var num = 12.749;
    parseFloat((Math.round(num * 100) / 100).toFixed(2)); // 123.75
    

    Round the number with 2 decimal points, then make sure to parse it with parseFloat() to return Number, not String unless you don't care if it is String or Number.

提交回复
热议问题