Format a Number, Exactly Two in Length?

前端 未结 10 646
既然无缘
既然无缘 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:07

    Just use the following short function to get the result you need:

    function pad2(number) {
        return (number < 10 ? '0' : '') + number
    }
    
    0 讨论(0)
  • 2021-02-03 22:07

    Improved version of previous answer:

    var result = [...Array(12)].map((_, i) => zeroFill(i + 1, 2));
    
    function zeroFill(num, size) {
      let s = num + '';
      while (s.length < size) s = `0${s}`;
      return s;
    }
    console.log(result)

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-03 22:09
    function padLeft(a, b) {
        var l = (a + '').length;
        if (l >= b) {
            return a + '';
        } else {
            var arr = [];
            for (var i = 0; i < b - l ;i++) {
                arr.push('0');
            }
            arr.push(a);
            return arr.join('');
        }
    }
    
    0 讨论(0)
  • 2021-02-03 22:10
    function pad(d) {
        return (d < 10) ? '0' + d.toString() : d.toString();
    }
    
    pad(1);  // 01
    pad(9);  // 09
    pad(10); // 10
    
    0 讨论(0)
  • 2021-02-03 22:11
    String("0" + x).slice(-2);
    

    where x is your number.

    0 讨论(0)
提交回复
热议问题