Reputation: 500
var x = 02345;
var y = x.toString();
alert(y);
I realized that there is a problem converting leading zeroes number to string in JavaScript using the toString() method.
As you can see from the output of the code above, the output is 1253
instead of the supposedly 02345
.
If the leading zero is removed, the code will work as expected, why? What is happening with the code above so I can change it to work as expected.
var x = 2345;
var y = x.toString();
alert(y);
EDIT : The reason I asked this question is because I have two different codes that work differently despite being very similar. After reading that this question has nothing to do with the toString() method, why does the first set of code below not detect the number as an octal value but the second set of code does.
var num=window.prompt(); // num = 0012222
var str = num.toString();
var result = [str[0]];
for(var x=1; x<str.length; x++)
{
if((str[x-1]%2 === 0)&&(str[x]%2 === 0))
{
result.push('-', str[x]);
}
else
{
result.push(str[x]);
}
}
alert(result.join('')); //Outputs : 0-012-2-2-2
The other code :
function numberDash(num) {
var stringNumber = num.toString();
var output = [stringNumber[0]];
for (var i = 1; i < stringNumber.length; i++) {
if (stringNumber[i-1] % 2 === 0 && stringNumber[i] % 2 === 0) {
output.push('-', stringNumber[i]);
} else {
output.push(stringNumber[i]);
}
}
return output.join('');
}
numberDash(0012222) // Outputs : "52-6-6";
Upvotes: 1
Views: 503
Reputation: 93
var x = 02345;
var y = x.toString("8");
alert(y);
This will give you 2345
Leading zero is interpreted as octal value.
If you need number converted to string with leading zero, use my method but simply modify it like this var y = "0" + x.toString("8")
Upvotes: 1
Reputation: 1073968
Many JavaScript engines add octal numeric literals to the specification. The leading zero indicates octal (base 8). 2345
in base 8 (octal) is 1253
in base 10 (decimal):
Octal Decimal ----- -------------------- 2 2 * 8 * 8 * 8 = 1024 3 3 * 8 * 8 = 192 4 4 * 8 = 32 5 5 ----- -------------------- 2345 1253
You can disable that using strict mode. See §B.1.1 of the specification. Doing so makes 02345
a syntax error.
So it's nothing to do with toString
, it's just that the 02345
in your code isn't the value you expect.
Re your updated question:
why does the first set of code below not detect the number as an octal value but the second set of code does
Because in the first code, you're not dealing with a number, you're dealing with a string. window.prompt
returns a string, not a number, even if what you type in is all digits.
Even if you converted the string to a number via Number(num)
or +num
, the rules for runtime string->number conversion are different from the rules for parsing JavaScript source code.
Upvotes: 2