-
Notifications
You must be signed in to change notification settings - Fork 28
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
On number parsing #86
Comments
What I propose, then, is:
|
The problem with coercion is that it doesn't give the same results as I propose returns an option. |
I'm not proposing that Then I'm also proposing that number coercion is used instead of |
Related bug report in |
This touches a bit on the discussion in #83, but covers more broadly the current options for parsing numbers in JavaScript, to try to inform which semantics we should expose, more so than just how we should type and organize the JS API.
Currently, I believe the only option for parsing numbers are
parseInt
/parseFloat
. Either directly throughFloat.parseFloat
andFloat.parseInt
, but also as the underlying API used inFloat.fromString
andInt.fromString
. While there unfortunately aren't any good options, in my opinionparseInt
andparseFloat
is the worst of all the bad options. For the sake of easy comparison and to facilitate efficient discussion, I've outlined the pros and cons of the options i know of below.Note that I've only covered the differences between the options. Common peculiarities to all of them is that:
NaN
.parseInt
/parseFloat
The core of the prom with these functions is described by the following quote from MDN:
While this may not seems like such a big issue, since it just ignores certain kinds of "mistakes", keep in mind that there isn't just one number format used across the world. These functions will only parse a very simple number format, close to but not entirely the same as JavaScript number literals. And iif it ecnounters anything that doesn't fit that, it will just ignore the rest. For example, if any kind of group separator is used, that and everything that follows will be silently ignored. The same goes for using a decimal separator other than
.
.In short, these invocations will all return
15
:Pros
Cons
Number coercion
There are a number of ways to trigger number coercion, such as using any numeric operator on them. E.g. if
value
is a string,+value
will return a number.This improves on
parseInt
andparseFloat
most notably by rejecting input that isn't wholly parsable, such as all the examples in the section above. It does come with a few extra cons though, but they are for the most part possible to work around.Pros
Cons
0x
etc.Number
constructorThis works very similar to number coercion, because that is the conversion mechanism actually used. But it's slightly slower. And when used as a constructor (with
new
) it will create aNumber
object rather than a primitive.Pros
Cons
The text was updated successfully, but these errors were encountered: