Format number to always show 2 decimal places

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

    Extend Math object with precision method

    Object.defineProperty(Math, 'precision',{
       value: function (value,precision,type){
                 var v = parseFloat(value),
                     p = Math.max(precision,0)||0,
                     t = type||'round';
                  return (Math[t](v*Math.pow(10,p))/Math.pow(10,p)).toFixed(p);
              }
        });
    
    console.log(
        Math.precision(3.1,3), // round 3 digits 
        Math.precision(0.12345,2,'ceil'), // ceil 2 digits
        Math.precision(1.1) // integer part
    )

提交回复
热议问题