Cappielung
Cappielung

Reputation: 342

Javascript variable not displaying the number assigned to it

I'm writing a javascript program that needs random 10-digit numbers which can sometimes have the 10th digit as 0. I assigned a variable to one of these numbers and then logged it to make sure everything was alright...but it wasn't. Here is my code:

var candidate = 0135740250;
var candidate2 = 0272189318;
console.log(candidate); // Returns 24625320
console.log(candidate2); // Returns 272189318

I tried taking the 0 off the beginning of candidate, and that made it return correctly, but I don't understand why it doesn't work in the first place. I included candidate2 above because whatever I do to it, adding 0s in the middle, changing it in other ways, it stays correct, so I can't figure out why candidate is being screwed up. I vaguely understand the number storage system in Javascript and that its not perfect, but I need a predictable, repeatable way to return the correct number.

The question is: what is happening here and how can I reliably avoid it?

Upvotes: 0

Views: 61

Answers (3)

Temitayo
Temitayo

Reputation: 812

Another quack is, if you know the length of string to generate

"use strict"
var strlent = 10
console.log(candidate2.toString().length < strlent ? "0" + 
candidate2.toString() : candidate2.toString())
>>>0272189318

Upvotes: 0

cookie monster
cookie monster

Reputation: 10972

"The question is: what is happening here..."

The first is a valid octal, so it gets converted as such.

The second is not a valid octal because of the 8 and 9, so it gets the base 10 representation with the leading 0 removed since it adds no value.


"...and how can I reliably avoid it?"

Avoiding it will depend on how you're generating your numbers. If you were using .random() it wouldn't be an issue, so I'd assume they're coming from some sort of string representation.

If so, and if you're using parseInt() to get the actual number, then pass it 10 as the second argument to ensure base-10 representation.

Upvotes: 4

Anthony Chu
Anthony Chu

Reputation: 37520

JavaScript treats any number beginning with 0 as octal if it is a valid octal.

Upvotes: 3

Related Questions