Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Number constructor fail to parse numbers with separators?

Since JavaScript has numeric separators (_, U+005F), why does Number("3_0") return NaN? Shouldn't it work like Number("0x08") which returns 8?

Number.isNaN(Number("3_0")) // true
Number.isNaN(Number(3_0))   // false
Number("3_0") === 30        // false
Number(3_0) === 30          // true
like image 753
Wersjon Avatar asked Aug 25 '26 19:08

Wersjon


1 Answers

According to the spec, there are a few differences between the syntax accepted for numeric literals and the syntax accepted for a string value when being converted to a numeric value.

One of the differences is

A StringNumericLiteral cannot include a NumericLiteralSeparator.

If I have to guess, the reason is that accepting such characters would change the behavior of existing valid JavaScript code, which may break working applications.

like image 141
Noam Avatar answered Aug 27 '26 08:08

Noam