Numbers in the form of 001

浪子不回头ぞ 提交于 2019-12-04 07:32:17

I think this is usually called "padding" the number.

Its called left zero padded numbers.

It's called padding.

Well, if you're talking about that notation within the context of certain programming languages, 020 as opposed to 20 would be Octal rather than Decimal.

Otherwise, you're referring to padding.

A quick google search revealed this nice snippet of code for Number Padding: http://sujithcjose.blogspot.com/2007/10/zero-padding-in-java-script-to-add.html

function zeroPad(num,count)
{
  var numZeropad = num + '';
  while(numZeropad.length < count) {
    numZeropad = "0" + numZeropad;
  }
  return numZeropad;
}

You can use a simple function like:

function addZ(n) {
  return (n<10? '00' : n<100? '0' : '') + n;
}

Or a more robust function that pads the left hand side with as many of whatever character you like, e.g.

function padLeft(n, c, len) {
  var x = ('' + n).length;
  x = (x < ++len)? new Array(len - x) : [];
  return  x.join(c) + n
}

Try this one:

Number.prototype.toMinLengthString = function (n) {
    var isNegative = this < 0;
    var number = isNegative ? -1 * this : this;
    for (var i = number.toString().length; i < n; i++) {
        number = '0' + number;
    }
    return (isNegative ? '-' : '') + number;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!