Reputation: 31
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
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
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:
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