Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 847
Tal Levi Avatar asked Sep 01 '26 22:09

Tal Levi


2 Answers

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
like image 76
Rocket Hazmat Avatar answered Sep 03 '26 12:09

Rocket Hazmat


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.

like image 23
Barmar Avatar answered Sep 03 '26 13:09

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!