Format number to always show 2 decimal places

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

    Try below code:

    function numberWithCommas(number) { 
    
       var newval = parseFloat(Math.round(number * 100) / 100).toFixed(2);
    
       return newval.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    

提交回复
热议问题