Format number to always show 2 decimal places

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

    RegExp - alternative approach

    On input you have string (because you use parse) so we can get result by using only string manipulations and integer number calculations

    let toFix2 = (n) => n.replace(/(-?)(\d+)\.(\d\d)(\d+)/, (_,s,i,d,r)=> {
      let k= (+r[0]>=5)+ +d - (r==5 && s=='-');
      return s + (+i+(k>99)) + "." + ((k>99)?"00":(k>9?k:"0"+k));
    })
    
    
    // TESTs
    
    console.log(toFix2("1"));
    console.log(toFix2("1.341"));
    console.log(toFix2("1.345"));
    console.log(toFix2("1.005"));

    Explanation

    • s is sign, i is integer part, d are first two digits after dot, r are other digits (we use r[0] value to calc rounding)
    • k contains information about last two digits (represented as integer number)
    • if r[0] is >=5 then we add 1 to d - but in case when we have minus number (s=='-') and r is exact equal to 5 then in this case we substract 1 (for compatibility reasons - in same way Math.round works for minus numbers e.g Math.round(-1.5)==-1)
    • after that if last two digits k are greater than 99 then we add one to integer part i

提交回复
热议问题