0

can someone tell me why this var val="08"; alert(parseInt(val-1)); shows 7 but var val="08"; alert(parseInt(val)-1); shows -1 ?

Thnx

Fozix
  • 133
  • 3
  • 12
  • No repro here on Firefox 26. Invalid octal literals such as `08` are tricky to work with, their support depends on the browser. Best to avoid them. – Frédéric Hamidi Jan 30 '14 at 10:48
  • 1
    I tried in Chrome Version 31.0.1650.63. It is giving 7 in both the cases. Fiddle: http://jsfiddle.net/jfu7t/ – Vinoth Jan 30 '14 at 10:49
  • Which browser (and version) are you using? In the first case, the string is implicitly converted to a number first, *before* the result of `val - 1` (`7`) is passed to `parseInt` and in the second example, `val` is first passed to `parseInt` and as result converted to a number. That's the difference and that's why you get different outputs in browsers that still implement the old `parseInt` method. – Felix Kling Jan 30 '14 at 10:49

2 Answers2

1

Always use parseInt(val,10); to ensure that value is parsed in decimal system. In your case when you alert val-1 i.e. 08-1 so it is 7 i.e. parseInt(7) ==> 7

but when you do

parseInt(val)-1  ==> parseInt("08")-1 ==> 0-1 ==> -1

why it becomes 0 ? The answer is it assumes you want to parse in Octal number system.

So always use the second argument i.e. parseInt(whatevervalue,10);

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
kcak11
  • 832
  • 7
  • 19
1

parseInt("08") will give you NaN if the engine you're using extends parseInt to recognize octal (the leading 0 means "octal"). It will give you 8 if the engine follows the standard, which says not to do that (as of ES5).

parseInt("08"-1) is a bit redundant, because the expression "08"-1 will result in a number (which then gets passed into parseInt); just "08"-1 is all you need. Here's how that breaks down:

  • The engine processes the expression "08" - 1 by trying to turn "08" into a number. On an engine that extends numeric literal syntax to include octal, that would fail, but on engines that don't, it will give you 8. So the result of the expression is the number 7 (8 - 1).

  • The engine then does parseInt(7), which is redundant, as 7 is already a number. What happens is that 7 is turned into "7" and then parsed back into 7.

Note the difference above: The result of parseInt("08") - 1 will vary based on whether the engine extends what parseInt will parse, but the result of "08" - 1 will vary based on whether the engine extends numeric literal syntax. Those are two different things, and the ES5 specification does not allow engines to extend parseInt's syntax, but does allow them to extend numeric literal syntax (see §B.1.1), but only in loose mode. (Confusing, I know.)

The take-away message: Always use a radix with parseInt to tell it what number base to use.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875