Format number to always show 2 decimal places

前端 未结 30 2843
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  -上瘾入骨i
    2020-11-21 08:27

    For modern browsers, use toLocaleString:

    var num = 1.345;
    num.toLocaleString(undefined, { maximumFractionDigits: 2, minimumFractionDigits: 2 });
    

    Specify a locale tag as first parameter to control the decimal separator. For a dot, use for example English U.S. locale:

    num.toLocaleString("en-US", { maximumFractionDigits: 2, minimumFractionDigits: 2 });
    

    which gives:

    1.35

    Most countries in Europe use a comma as decimal separator, so if you for example use Swedish/Sweden locale:

    num.toLocaleString("sv-SE", { maximumFractionDigits: 2, minimumFractionDigits: 2 });
    

    it will give:

    1,35

提交回复
热议问题