Format number to always show 2 decimal places

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

    You can try this code:

        function FormatNumber(number, numberOfDigits = 2) {
            try {
                return new Intl.NumberFormat('en-US').format(parseFloat(number).toFixed(2));
            } catch (error) {
                return 0;
            }
        }
    
        var test1 = FormatNumber('1000000.4444');
        alert(test1); // 1,000,000.44
    
        var test2 = FormatNumber(100000000000.55555555, 4);
        alert(test2); // 100,000,000,000.56
    

提交回复
热议问题