Skip to content

Commit f06324d

Browse files
fix: Fix FP issues
1 parent e169e56 commit f06324d

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

src/main/java/net/marcellperger/mathexpr/util/MathUtil.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,22 @@
22

33
import org.jetbrains.annotations.Range;
44

5+
import java.math.BigDecimal;
6+
import java.math.RoundingMode;
7+
58
public class MathUtil {
69
protected MathUtil() {}
710

8-
// TODO this doesn't work: roundToSigFigs(1.22222 + 0.3, 10) == 1.5222200000000001
911
public static double roundToSigFigs(double value, @Range(from=1, to=Integer.MAX_VALUE) int sigFigs) {
1012
int mostSignificantDigit = (int)Math.floor(Math.log10(value));
1113
int roundToDigit = mostSignificantDigit - sigFigs + 1;
1214
return roundToDP(value, roundToDigit);
1315
}
1416

1517
public static double roundToNearest(double value, double nearest) {
16-
return Math.round(value / nearest) * nearest;
18+
BigDecimal nearestD = BigDecimal.valueOf(nearest);
19+
return BigDecimal.valueOf(value).divide(nearestD, RoundingMode.HALF_UP)
20+
.setScale(0, RoundingMode.HALF_UP).multiply(nearestD).doubleValue();
1721
}
1822
public static double roundToDP(double value, int decimalPlaces) {
1923
return roundToNearest(value, Math.pow(10, decimalPlaces));

0 commit comments

Comments
 (0)