1

How to convert numbers like 007514,0129, 00 to string?

How do I get pinToStr to return '0746'?

//incorrect output
var pin = 0746;
var pinToStr = pin.toString()
console.log(pinToStr); //486


//correct output
var pin1 = 7460;
var pinToStr1 = pin1.toString()
console.log(pinToStr1); //7460

//incorrect output

let pin = 0746;
let pinToStr = pin.toString()
console.log(pinToStr); //486

//correct output
let pin1 = 7460;
let pinToStr1 = pin1.toString()
console.log(pinToStr1); //7460
Abk
  • 2,137
  • 1
  • 23
  • 33
  • You could try -> `var pin = 746; console.log(('0000' + pin.toString()).slice(-4))` – Keith Nov 07 '18 at 14:28
  • 2
    Better question is why are you storing PIN as a number? – Roberto Zvjerković Nov 07 '18 at 14:29
  • When `pin` gets its value assigned to `0746`, it's a number. By definition, numbers don't have leading zeroes, otherwise where would you stop? What you'd want to do is left pad the number with zeroes to create a 4 character long string. – krillgar Nov 07 '18 at 14:29
  • 1
    `//incorrect output` - nope, incorrect _input_ to begin with. You are getting 486 as result, because the number you “input” was in the _octal_ system, because that’s what a leading zero means in JavaScript. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Numeric_literals – misorude Nov 07 '18 at 14:31
  • @misorude, thank you for the information. Now I understand – Abk Nov 07 '18 at 14:32
  • @ritaj, thank you. I'll be storing PIN as a string henceforth. – Abk Nov 07 '18 at 14:35
  • The duplication mark is in my opinion not correct here, as the question is not how to zerofill but rather how to handle a logical number with leading zeros. That is quite a difference. – lumio Nov 07 '18 at 14:38

2 Answers2

3

In JavaScript, when you start a number with a leading zero, it is meant to be a number in octal (base 8). That's the reason why 0746 (in octal) is actually 486 in decimal.

To check my assumption, here a little example:

010 === 8 // true

What you really want to do is to write that number as a string from the beginning on.

var pin = '0746';
console.log(pin); // 0746
lumio
  • 7,428
  • 4
  • 40
  • 56
2

The thing is that you are storing integers, which can't have preceding zeroes. save them as strings in the first place.

var pin1 = "7460";
console.log(pin1); //7460
Dennis Lukas
  • 483
  • 2
  • 6
  • 20