Format number to always show 2 decimal places

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

    function currencyFormat (num) {
        return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
    }
    
    console.info(currencyFormat(2665));   // $2,665.00
    console.info(currencyFormat(102665)); // $102,665.00
    

提交回复
热议问题