0

I was writing some Javascript when I accidentally typed 04.5 instead of 40.5. When I ran the code, it produced a SyntaxError that read Uncaught SyntaxError: Unexpected number. I tested this in Chrome, Safari, Firefox, and NodeJS, and they all produced the same error. I looked through the Javascript specifications, but I couldn't find anything on it. What is Javascript interpreting a decimal number with a 0 before it as?

04.5 // Uncaught SyntaxError: Unexpected number
shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34

2 Answers2

3

With a leading zero it's interpreted as octal. But it seems that octals are not liked with decimal places.

Sascha
  • 4,576
  • 3
  • 13
  • 34
0

It's because of the leading zeros. This works fine:

JSON.parse('[04.5]');

JSON definition says integers must not have leading zeros

EDIT To remove the leading zeros in case you have an array of numbers starting with 0 :

var str = '[04,05,06,07,08,09]';
str = str.replace(/\b0(\d)/g, "$1");
JSON.parse(str);
Momo
  • 66
  • 1
  • 9