开发者

Numbers in the form of 001

开发者 https://www.devze.com 2023-03-22 17:03 出处:网络
Is there a special name for numbers in the format of 001. For example the number 20 would be 020 and 1 would be 001. Its hard to Google around when you don`t know somethings name! Since I am already

Is there a special name for numbers in the format of 001. For example the number 20 would be 020 and 1 would be 001.

Its hard to Google around when you don`t know somethings name!

Since I am already wasting your guys time does any one know a function for changing numbers to thi开发者_JAVA技巧s format.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消