From b561cdb6f3fef251696216775c775f84369278cc Mon Sep 17 00:00:00 2001 From: Chris Laplante Date: Wed, 2 Oct 2019 21:38:11 -0400 Subject: [PATCH 1/2] Fix bad implementation of compareTo in BigDecimal Prior to this patch compareTo couldn't handle operands with negative scales. It passes the following unit test from JDK8: http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/test/java/math/BigDecimal/CompareToTests.java Upstream-Status: Inappropriate [dead project] Signed-off-by: Chris Laplante --- java/math/BigDecimal.java | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/java/math/BigDecimal.java b/java/math/BigDecimal.java index 7f4546c..e14d894 100644 --- a/java/math/BigDecimal.java +++ b/java/math/BigDecimal.java @@ -861,26 +861,30 @@ public class BigDecimal extends Number implements Comparable if (scale == val.scale) return intVal.compareTo (val.intVal); - BigInteger thisParts[] = - intVal.divideAndRemainder (BigInteger.TEN.pow (scale)); - BigInteger valParts[] = - val.intVal.divideAndRemainder (BigInteger.TEN.pow (val.scale)); + BigInteger[] thisParts = new BigInteger[2]; + BigInteger[] valParts = new BigInteger[2]; + + if (scale > 0) + thisParts = intVal.divideAndRemainder (BigInteger.TEN.pow (scale)); + else + { + thisParts[0] = intVal.multiply (BigInteger.TEN.pow (-scale)); + thisParts[1] = BigInteger.ZERO; + } + + if (val.scale > 0) + valParts = val.intVal.divideAndRemainder (BigInteger.TEN.pow (val.scale)); + else + { + valParts[0] = val.intVal.multiply (BigInteger.TEN.pow (-val.scale)); + valParts[1] = BigInteger.ZERO; + } int compare; if ((compare = thisParts[0].compareTo (valParts[0])) != 0) return compare; // quotients are the same, so compare remainders - - // Add some trailing zeros to the remainder with the smallest scale - if (scale < val.scale) - thisParts[1] = thisParts[1].multiply - (BigInteger.valueOf (10).pow (val.scale - scale)); - else if (scale > val.scale) - valParts[1] = valParts[1].multiply - (BigInteger.valueOf (10).pow (scale - val.scale)); - - // and compare them return thisParts[1].compareTo (valParts[1]); } -- 2.7.4