unitsofmeasurement / indriya

JSR 385 - Reference Implementation
Other
119 stars 42 forks source link

BigDecimal to BigInteger comparisons are incorrect #359

Closed mborger closed 3 years ago

mborger commented 3 years ago

I have discovered a case where Quantity of 42.42 is not considered less than a Quantity of Double.MAX_VALUE.

ComparableQuantity<Dimensionless> maxDoubleQuantity = Quantities.getQuantity(Double.MAX_VALUE, ONE);
Quantities.getQuantity(BigDecimal.valueOf(42.42), ONE).isLessThan(maxDoubleQuantity); // returns false

I believe this result is incorrect and the library should return true in this case.

From my research, the maxDoubleQuantity is narrowed to a BigInteger. The DefaultNumberSystem assumes that a long value can be retrieved from a BigInteger to construct a BigDecimal for comparison. BigInteger returns the lower 64 bits upon conversion to a long value which results in a value of 0, instead an equivalent representation of Double.MAX_VALUE.

I worked around this issue by changing the consumer to define their maximum value as Long.MAX_VALUE. I am working on a pull request to fix the above issue.

andi-huber commented 3 years ago

Excellent find! Confirmed bug. Let me check your PR.

andi-huber commented 3 years ago

fixed