最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Numbers in the form of 001 - Stack Overflow

programmeradmin0浏览0评论

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 this format.

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 this format.

Share Improve this question asked Jul 25, 2011 at 23:22 James AndinoJames Andino 25.8k17 gold badges54 silver badges79 bronze badges
Add a comment  | 

7 Answers 7

Reset to default 6

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)

  1. 暂无评论