Format number to always show 2 decimal places

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

    For the most accurate rounding, create this function:

    function round(value, decimals) {
        return Number(Math.round(value +'e'+ decimals) +'e-'+ decimals).toFixed(decimals);
    }
    

    and use it to round to 2 decimal places:

    console.log("seeked to " + round(1.005, 2));
    > 1.01
    

    Thanks to Razu, this article, and MDN's Math.round reference.

提交回复
热议问题