Hi,

Converting an arbitray value to a number in JS can be rather inconsistent and unexpected:

* `null` and `undefined` are different: `+null === 0` but `+undefined` is NaN.

* Empty string and non-nubmeric strings are different: `+"" === 0` but `+"foo"` is NaN.


This problem can be worse because JSON only support finite numbers:

```

var total = 0;

total += JSON.parse(JSON.stringify({ "value": 0/0 })).value;

total === 0; //Oops, NaN is serialized as null, and then converted to 0

```

So I propose a more consistent and stricter number converting function: `Number.of(value)`:

1. If `value` is `null` or `undefined`, return `NaN`;

2. If `value` is a number, return `value` itself;

3. If `value.valueOf()` returns a number, return that number, otherwise return `NaN`.


This means all non-number values except those have number type `.valueOf()` would be converted to NaN:


```

Number.of(null); // NaN

Number.of(''); //NaN

Number.of('1'); //NaN


var total = 0;

total += Number.of(JSON.parse(JSON.stringify({ "value": 0/0 })).value);

total; // NaN

```


What do you think?


Regards,

Duan, Yao



_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to