2

I am interesting in understanding why 032*2 returns 52 in JavaScript.

I have a feeling that 032 could be interpenetrated as octal notation but I could not find a proper reference to it.

Could you please:

  • Provide me an explanation with references.

Thanks in advance your help on this.

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • RE: your feeling did you google `octal notation javascript`? Top 3 results for me all explain it and MDN is amongst them. – Martin Smith Jul 14 '15 at 06:26
  • thanks for posting a related questions/answer, but I believe my question is not duplicated... I also eed link/reference to some documentation other than an explanation. – GibboK Jul 14 '15 at 06:27
  • 032 = (3*(8^1)+2*(8^0)) = ((3*8)+2*1)=(24+2)=26.So , 032*2 = 52 – RIYAJ KHAN Jul 14 '15 at 06:28
  • questions asking us to recommend an off site resource are also off topic. – Martin Smith Jul 14 '15 at 06:29
  • @MartinSmith thanks for commenting, I was not aware of this rule about link to external resources. – GibboK Jul 14 '15 at 06:35

3 Answers3

5

Numbers starting with 0 are Octal. So, 032 === 26.

To convert it into Base-10/Decimal number use parseInt with radix 10.

parseInt('032', 10) * 2; // 64

From MDN Docs:

If radix is undefined or 0 (or absent), JavaScript assumes the following:

  1. If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
  2. 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.
  3. If the input string begins with any other value, the radix is 10 (decimal).
Tushar
  • 85,780
  • 21
  • 159
  • 179
2

Octal interpretations with no radix

Although discouraged by ECMAScript 3 and forbidden by ECMAScript 5, many implementations interpret a numeric string beginning with a leading 0 as octal.The following may have an octal result, or it may have a decimal result.
Always specify a radix to avoid this unreliable behavior.

Source: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/parseInt

spcial
  • 1,529
  • 18
  • 40
2

ECMAScript 5.1 specifies some extensions to Numeric literals in its annex:

The syntax and semantics of 7.8.3 [Numeric literals] can be extended as follows except that this extension is not allowed for strict mode code:

NumericLiteral ::
   DecimalLiteral
   HexIntegerLiteral
   OctalIntegerLiteral
OctalIntegerLiteral ::
   0 OctalDigit
   OctalIntegerLiteral OctalDigit

This concludes that any number which starts with a 0 and is followed by OctalDigits can be considered an octal one. However, this is not allowed in strict mode.

Zeta
  • 103,620
  • 13
  • 194
  • 236