MikeMcl / decimal.js

An arbitrary-precision Decimal type for JavaScript
http://mikemcl.github.io/decimal.js
MIT License
6.45k stars 475 forks source link

(bug?) negated zero is negative #147

Closed Mazuh closed 4 years ago

Mazuh commented 4 years ago

why would 0 * (-1) (as is negated() documented behavior) be considered negative?

Decimal('0').negated().isNegative() // true (1)
Decimal('0').isNegative() // false (2)

and that is a contradition when I compare 0 with itself, negated or not:

Decimal('0').negated().lessThan(Decimal('0')) // false (3)
Decimal('0').lessThan(Decimal('0')) // false (4)
Decimal('0').negated().lessThan(Decimal('0').negated()) // false (5)

the only weird behavior here is the first (1) example, the other 4 lines seem ok.

Mazuh commented 4 years ago

I'd be happy to fix it, but it's too weird that I'm starting to think that's intentional, tho a contradiction... may I have some confirmation here, @MikeMcl ?

MikeMcl commented 4 years ago

No fix required, thanks.

The isNegative method looks only at the sign of a value. not its magnitude. If it did not consider -0 negative then it would be difficult to distinguish it from +0 as they are considered equal.

Decimal(0).negated().valueOf();    // '-0'

See signed zero from Wikipedia or Is Negative Zero a Number in JavaScript?

Mazuh commented 4 years ago

Very interesting, didn't know that. Thank you for the detailed answer and the nice article.

May you consider at least a doc update? I mean, I found your lib while trying to bypass float type limitations, so it's weird to just be ok with that without a clear documented warning or something.

Mazuh commented 4 years ago

considering this a no-fix, I opened a small proposal to add this warning on readme (so we can properly close this issue on merge).

Hope you consider it!