avar = "0000013482000000";
t = parseInt(avar);
When I run that, t
is 92
for some reason. If I remove the leading 0's, then it works just fine. Why would that be?
avar = "0000013482000000";
t = parseInt(avar);
When I run that, t
is 92
for some reason. If I remove the leading 0's, then it works just fine. Why would that be?
Use the second parameter (radix):
t = parseInt(avar, 10);
To specify that the number should be parsed in base 10.
From the MDN docs:
If radix is undefined or 0 (or absent), JavaScript assumes the following:
And in reference to ECMAScript 5:
The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading white space in string is ignored. If radix is undefined or 0, it is assumed to be 10 except when the number begins with the character pairs 0x or 0X, in which case a radix of 16 is assumed. If radix is 16, number may also optionally begin with the character pairs 0x or 0X.
Reference:
Try this:
avar = "0000013482000000";
t = parseInt(avar,10);
Some browsers might assume that it is an octal number if the string starts with 0
.
However, ,10
is not required in modern browsers with new ECMAScript standards because they will always be considered as decimal unless specified or starts with 0x
(hexadecimal).
Chrome is one of those browsers that has a default radix of 10.
Reference: ECMAScript Language Specification Page 104
The
parseInt
function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading white space in string is ignored. If radix is undefined or 0, it is assumed to be 10 except when the number begins with the character pairs 0x or 0X, in which case a radix of 16 is assumed. If radix is 16, the number may also optionally begin with the character pairs 0x or 0X.
Parsing a number with leading zeros causes the number to be treated as octal. To override this you need to set the radix parameter of parseInt
to 10 (base 10 as opposed to base 8).
parseInt
assumes octal notation if you have a leading zero, so you want to pass in a radix
as the second parameter, telling the function to parse the string as a base 10 int.
parseInt(avar, 10)
should fix it.