Question

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?

Was it helpful?

Solution

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).

enter image description here

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.

OTHER TIPS

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:

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
  • If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
  • If the input string begins with any other value, the radix is 10 (decimal).

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:

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top