3

I have an array of numbers and some of them has leading zeros. How can I make them to string without losing leading zeros?

var array = [10, 00002, 30, 400, 5000];
array[1].toString; // would be 2 instead of 0002 as JS drops leading zeros

I have looked other solutions (JavaScript Number preserve leading 0, JavaScript: Keeping the leading zero in a number and JavaScript Number preserve leading 0), and they all suggest to make the number string.

But in my case the numbers in array would be provided by user, so when they're go through .toString they lose leading zeros.

How can I get around this so when I slice the first 2 digits of each elements they final array would be:

var twoDigitArray = ["10", "00", "30", "40", "50"];

?

Community
  • 1
  • 1
Amma
  • 177
  • 16
  • 3
    Do you know that leading zeros in js means octal, i.e. 0012 === 10 – Musa Feb 16 '17 at 18:39
  • How are receiving these from the user? If it's in an input or other form element, then they start a string. – KevBot Feb 16 '17 at 18:50
  • Leading zeros have no significant value. You need to understand the difference between internal numerical value which is used for computation and string based display format which is decoration. There is a reason all those solutions use strings to preserve leading zeros. Your user input must be stored in a string that you, as the programmer, can convert as necessary. – fnostro Feb 16 '17 at 18:51
  • Just to emphasize the point made by @Musa, `var array = [016, 017, 018, 019, 020, 021]; console.log(array);` yields the following: `[ 14, 15, 18, 19, 16, 17 ]` ! – Andrew Willems Feb 16 '17 at 19:23

1 Answers1

0

You can create a zero fill function

function zeroFill(number, width) {
  width -= number.toString().length;
  if (width > 0) {
    return new Array(width + (/\./.test(number) ? 2 : 1)).join('0') + number;
  }
  return number.toString();
}

And then you can slice your returned number

number.slice(0, 2);
greatgumz
  • 408
  • 3
  • 17