0

How can I force JavaScript to keep 0 before numbers in the Int type?

I have some numeric map codes which all starting by 0 so I need to pass them as a part of the number for each code.

var mapcode = "042";
mapcode = parseInt(mapcode);
console.log(mapcode);
halfer
  • 19,824
  • 17
  • 99
  • 186
Mona Coder
  • 6,212
  • 18
  • 66
  • 128
  • Apparently the receiving function expects a string anyway. Otherwise it wouldn't require the zeroes. A number with leading zeroes isn't technically an integer. – isherwood Nov 15 '17 at 19:06

3 Answers3

2

As I know the only way is keeping it as string or adding the 0 just before showing it

var mapcode = "042";
mapcode = parseInt(mapcode);
console.log(0 + mapcode.toString());
Alvar
  • 41
  • 7
1

You cannot. You need to keep it as string if you need a leading zero.

Battle_Slug
  • 2,055
  • 1
  • 34
  • 60
  • This is true, but doesn't answer the spirit or practicality of the question. What if OP needs to do calculations on the numbers involved and then print the number with prepending zeros? – Kallmanation Nov 15 '17 at 19:09
0

As has been said, javascript just keeps the integer and therefore prepending zeros are 'removed' because they are meaningless to a number. (i.e. 42 = 042 = 0042 = 0000000042).

So what you need is to either keep these numbers as strings, in which case every character (including prepended zeros) are meaningful. Or you will need to prepend the appropriate number of zeros to the number before displaying it.

You can see this question to find several methods for prepending zeros to a number for printing.

Kallmanation
  • 1,132
  • 7
  • 11