Tal Levi
Tal Levi

Reputation: 31

Javascript evaluate number starts with zero as a decimal

I want to evaluate number starts with zero as a decimal number.

For example, let's define convertToDec

convertToDec(010) => 10 
convertToDec(0010) => 10
convertToDec(0123) => 123

etc..

Because all js numbers starts with 0 are evaluated in base 8, I tried to do it like this:

function convertToDec(num){
    return parseInt(num.toString(), 10);
}

But the toString function parses the number in base 8.

Any suggestions?

Thanks!

Upvotes: 3

Views: 378

Answers (2)

Barmar
Barmar

Reputation: 782130

You need to call convertToDec with string arguments, not numbers.

function convertToDec(num){
    return parseInt(num, 10);
}
alert(convertToDec("010"));

If you give it a number as the argument, the number has already been parsed by the Javascript interpreter, the function can't get back what you originally typed. And the JS interpreter parses numbers beginning with 0 as octal.

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227310

If you literally write 0010 in JavaScript, then it will be treated as an octal number. That's just how the parser works.

From MDN's docs:

  • Decimal integer literal consists of a sequence of digits without a leading 0 (zero).
  • Leading 0 (zero) on an integer literal indicates it is in octal. Octal integers can include only the digits 0-7.
  • Leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F.
  • Leading 0b (or 0B) indicates binary. Binary integers can include digits only 0 and 1.

So, when you write convertToDec(0010), your browser interprets this as convertToDec(8). It's already been "converted" to an 8 since you used an "octal literal".

If you want the literal value "0010", then you'll need to use a string.

parseInt("0010", 10); // 10

Upvotes: 4

Related Questions