Format number to always show 2 decimal places

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

    This answer will fail if value = 1.005.

    As a better solution, the rounding problem can be avoided by using numbers represented in exponential notation:

    Number(Math.round(1.005+'e2')+'e-2'); // 1.01
    

    Cleaner code as suggested by @Kon, and the original author:

    Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)
    

    You may add toFixed() at the end to retain the decimal point e.g: 1.00 but note that it will return as string.

    Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces).toFixed(decimalPlaces)
    

    Credit: Rounding Decimals in JavaScript

提交回复
热议问题