4
console.log(0700/100) // result: 4.48
console.log(0900/100) // result: 9

I was learning vue by creating a calculator app and was using an array to store the variable. When I was testing it by entering 0s before the actual operand, I got confused by the above behaviour.

Mark Ormesher
  • 2,289
  • 3
  • 27
  • 35
jeff
  • 87
  • 1
  • 11

2 Answers2

2

Because 0700 starts with a zero, JS treats it as an octal (base-8) number. 0900 couldn't be octal, so JS treats it as regular decimal (base-10) number.

0700 octal = 448 decimal, so 0700 (octal) / 100 (decimal) = 4.48

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Mark Ormesher
  • 2,289
  • 3
  • 27
  • 35
  • I suppose, real question is why 0900 is interpreted as decimal instead of throwing error about broken octal... – Artur Biesiadowski Nov 15 '19 at 12:56
  • @ArturBiesiadowski There's some interesting context and history in this question and its answers: https://stackoverflow.com/questions/37003770/why-javascript-treats-a-number-as-octal-if-it-has-a-leading-zero. Short version is use strict mode and this goes away. – Mark Ormesher Nov 15 '19 at 12:59
  • I see, thanks a bunch sir. Can I ask why it treats 0700 as an octal just because it starts with a 0. Thanks again sir. – jeff Nov 15 '19 at 13:00
  • @ArturBiesiadowski Because that’s what has been specified since the beginning of JavaScript. Modern features don’t use this behavior. – Sebastian Simon Nov 15 '19 at 13:00
  • I see, weird but thanks a lot – jeff Nov 15 '19 at 13:02
  • Does decimal number have the number 10 as a single digit? no. Octal doesn't either. The largest single digit in Octal is 7. The numbers go from 0-7 and not from 0-8. I fixed your example :) – mplungjan Nov 15 '19 at 13:05
0

When you put a 0 before a number, js casts it to octal, which is equal to 448. But 0900 contains 9 so it cannot be octal, thus it will be equal to 900.

ganjim
  • 1,234
  • 1
  • 16
  • 30