Format number to always show 2 decimal places

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

    Here's also a generic function that can format to any number of decimal places:

    function numberFormat(val, decimalPlaces) {
    
        var multiplier = Math.pow(10, decimalPlaces);
        return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
    }
    

提交回复
热议问题