tc39 / proposal-number-fromstring

{BigInt,Number}.fromString(string, radix)
https://mathiasbynens.github.io/proposal-number-fromstring/
65 stars 7 forks source link

Consider not allowing leading zeros #8

Closed domenic closed 6 years ago

domenic commented 6 years ago

In a similar vein to #5 and #6, if this is supposed to be symmetric with Number.prototype.toString(), then it should not accept leading zeros.

I also can't find where leading zeros are handled in the spec, unless the idea is that 06 is supposed to be a "mathematical integer value", which I don't think is true. I based this just on

In other words, Number.fromString('010') results in 10 (and not 8).

from the readme.

littledan commented 6 years ago

The "mathematical integer value" text seems to be cribbed from the definition of parseInt; seems fine to me (except it is ugly how that becomes ambiguous with decimals). For me, the most important downside is the ambiguity with octal literals. I wouldn't mind a SyntaxError on leading 0 for that reason.

EDIT: I didn't realize until later that the "mathematical integer value" is intended to interpret things like Infinity. This seems not so great. Also, I'd like to go back and fix parseInt.

mathiasbynens commented 6 years ago

a29f339980abb55d93f50c650294eedf071363d5 includes this change. Please take a look and let me know of any issues.

@littledan I agree it feels ugly to use “mathematical integer/number value”. Suggestions for a less ambiguous way of specifying this are welcome! I’ve opened #16 for this.

zloirock commented 6 years ago

That looks too strange. In the README:

Number.fromString('00101010', 2);
// → 42 === 0b00101010

fromString intentionally lacks special handling for legacy octal integer literals, i.e. those without the explicit 0o or 0O prefix such as 010. In other words, Number.fromString('010') throws a SyntaxError exception.

In the first case, Number.fromString ignores 2 leading zeroes, in the second throws SyntaxError on 1 leading zero. The difference only in the existent second argument. I don't see anything related leading zeroes handling in the spec text. So how it should work?