Format a Number, Exactly Two in Length?

前端 未结 10 678
既然无缘
既然无缘 2021-02-03 21:49

I have an integer that is less then 100 and is printed to an HTML page with JavaScript. How do I format the integer so that it is exactly two digits long? For example:

10条回答
  •  一个人的身影
    2021-02-03 22:08

    A direct way to pad a number to the left in Javascript is to calculate the number of digits by log base 10. For example:

    function padLeft(positiveInteger, totalDigits) {
      var padding = "00000000000000";
      var rounding = 1.000000000001;
      var currentDigits = positiveInteger > 0 ? 1 + Math.floor(rounding * (Math.log(positiveInteger) / Math.LN10)) : 1;
      return (padding + positiveInteger).substr(padding.length - (totalDigits - currentDigits));
    }
    

    The rounding factor fixes the problem that there is no way to get an exact log of powers of 10, for example Math.log(1000) / Math.LN10 == 2.9999999999999996 Of course one should add validation of the parameters.

提交回复
热议问题