-3

I am writing a for loop which return numbers from 1 to 999. I want numbers to be returned in 3 digits i.e., from 001 to 999. How can I convert the returned value in 3 digit places?

Niks
  • 41
  • 2
  • 11

1 Answers1

2

A simple function to pad +ve integers is:

function pad(n, length) {
  var len = length - (''+n).length;
  return (len > 0 ? new Array(++len).join('0') : '') + n
}

pad(32, 6) // '000032'
pad(32, 1) // '32'

If you need to maintain the sign, or deal with decimals, a little more work is required.

RobG
  • 142,382
  • 31
  • 172
  • 209