0
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?

Shamoon
  • 41,293
  • 91
  • 306
  • 570

4 Answers4

1

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:

Ian
  • 50,146
  • 13
  • 101
  • 111
1

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.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
1

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

Rick Viscomi
  • 8,180
  • 4
  • 35
  • 50
1

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.

coderzach
  • 388
  • 4
  • 6