-1

I'm writing a javascript who is supposed to just print on a raw web-page and I'm finding some formatting problems. I would like to know if there's a way to do something like printf("%4d",num) in Javascript, because I always need to print a number considering it with 4 digits. It would be something like that:

Year

  1

Instead of:

Year

1

Andy
  • 49,085
  • 60
  • 166
  • 233
Sergio
  • 21
  • 1
  • 6
  • 3
    So you don't *really* mean "4 digits", you mean you want the numbers to consume 4 digits worth of space, right? A four-digit `1` would be `0001`. – Pointy Apr 20 '15 at 14:56
  • `sprintf` is a function available in many languages, but explaining how to reimplement it in JavaScript is probably too broad for a Stackoverflow question. Of course, it sounds like something someone might have implemented already if you [searched for it](https://duckduckgo.com/?q=javascript+sprintf&ia=qa). – Quentin Apr 20 '15 at 14:58
  • possible duplicate of [JavaScript equivalent to printf/string.format](http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format) – Matthew Apr 20 '15 at 15:00
  • Pointly you're right, sorry for my english. I could also print 0001, it would be the same – Sergio Apr 20 '15 at 15:08

1 Answers1

1

If you simply want all numbers to be 4 digits long, you need to prepend zeros until the number is 4 digits long.

function padNumber(number) {
    number = number.toString();

    while(number.length < 4) {
        number = "0" + number;
    }

    return number;
}

The conversion to string is necessary to make sure that:

  • the number variable has a length property (numbers do not)
  • the JS engine doesn't convert the return value to base form again (i.e. 0004 -> 4)
ArtOfCode
  • 5,702
  • 5
  • 37
  • 56