Why does a decimal number with a 0 before it produce a SyntaxError?

113 Views Asked by At

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

2

There are 2 best solutions below

0
Sascha On BEST ANSWER

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

3
Momo On

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