MikeMcl / bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
http://mikemcl.github.io/bignumber.js
MIT License
6.64k stars 741 forks source link

fix: Sum of zero elements equals zero #294

Closed artyomxyz closed 11 months ago

artyomxyz commented 3 years ago

I believe sum of zero elements equals zero. Current implementation produces NaN for this case.

shuckster commented 3 years ago

In plain JavaScript, how does the length of a set correlate with its type?

MikeMcl commented 3 years ago

I don't think that convention would be useful here. I think it is better to indicate a probable mistake with NaN.

The current behaviour is consistent with other operations, e.g. BigNumber(1).plus() // NaN.

artyomxyz commented 3 years ago

I don't think that convention would be useful here. I think it is better to indicate a probable mistake with NaN.

The current behaviour is consistent with other operations, e.g. BigNumber(1).plus() // NaN.

Big difference here is that .plus expects exactly one number, while sum expects set of numbers. And it is consistent with mathematical definition of sum.

Imagine we have a cart and products in it. We want to display total price of products. BigNumber.sum(...cart.products.map(p => p.price)). For empty cart it's NaN. What kind of error we want to indicate here? Still if we pass undefined as first argument we would receive NaN because it's an error

https://en.wikipedia.org/wiki/Empty_sum

MikeMcl commented 3 years ago

Big difference here is that .plus expects exactly one number, while sum expects set of numbers.

Here, sum expects one or more numbers.

Imagine we have a cart and products in it.

Right, it's shopping, not formal mathematics.

For empty cart it's NaN. What kind of error we want to indicate here?

That there is nothing to sum?

Still if we pass undefined as first argument we would receive NaN because it's an error.

NaN is returned because undefined is not a number.

I agree that in some situations it would be useful for zero to be returned, but it would need to be applied consistently so:

BigNumber();           // 0
BigNumber(1).plus();   // 1
BigNumber.sum();       // 0
// etc.

I will consider it further but I am not convinced atm.