Skip to content
This repository has been archived by the owner on Oct 10, 2019. It is now read-only.

Why doesn't Number throw on BigInts it can't represent precisely? #192

Closed
tjcrowder opened this issue Jan 25, 2019 · 3 comments
Closed

Why doesn't Number throw on BigInts it can't represent precisely? #192

tjcrowder opened this issue Jan 25, 2019 · 3 comments

Comments

@tjcrowder
Copy link

BigInt throws when given a number it can't represent precisely:

console.log(BigInt(1.2)); // RangeError: The number 1.2 cannot be converted to a BigInt because it is not an integer

Why does Number not throw when given a BigInt it can't represent precisely?

const big = 2n**53n + 1n;
console.log(big);         // 9007199254740993n
console.log(Number(big)); // 9007199254740992

It's not like Number doesn't throw in other cases (Number(Symbol()), Number({valueOf: function() { throw Error(); }}))...

Is it because of the inherently-imprecise nature of Number? And the largely-inherently-precise nature of BigInt? (Although given 5n / 2n === 2n, BigInt isn't always precise...)

#132 and #15 touched on this, but I don't think quite addressed it. Apologies in advance if I've missed it or am being dense, as seems likely.

(To be clear, I'm not saying it should throw on all "unsafe" integers, Number(2n**53n + 2n) should continue to work. Just asking why it doesn't throw when precision loss would occur, like BigInt does.)

@littledan
Copy link
Member

There were some important use cases to have an explicit rounding operation, so the Number constructor does that. We debated this question back and forth in various issues on this repository.

@tjcrowder
Copy link
Author

tjcrowder commented Jan 26, 2019

Okay, thanks. The inconsistency just tripped me up trying to explain BigInt, hence my (probably sophomoric) attempts to explain above with the "nature" thing. :-) I don't see a discussion of using Number vs. a separate rounding function in the issues, but really that would just be for my curiousity...

@littledan
Copy link
Member

Well, maybe we can talk about how the docs can be improved for clarity, cc @sarahgp

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants