Change roundTo method to use BigDecimal rather than Double for more accurate comparison. Update tests to introduce more scenarios where without the code change, they'd fail.

This commit is contained in:
boc-the-git 2019-11-12 15:39:42 +11:00
parent eb98ca7658
commit b682432ca0
2 changed files with 22 additions and 6 deletions

View file

@ -1,15 +1,24 @@
package info.nightscout.androidaps.utils; package info.nightscout.androidaps.utils;
import java.math.BigDecimal;
/** /**
* Created by mike on 20.06.2016. * Created by mike on 20.06.2016.
*/ */
public class Round { public class Round {
public static Double roundTo(double x, Double step) { public static Double roundTo(double x, Double step) {
if (x != 0d) { if (x == 0d) {
return Math.round(x / step) * step;
}
return 0d; return 0d;
} }
//Double oldCalc = Math.round(x / step) * step;
Double newCalc = BigDecimal.valueOf(Math.round(x / step)).multiply(BigDecimal.valueOf(step)).doubleValue();
// just for the tests, forcing failures
//newCalc = oldCalc;
return newCalc;
}
public static Double floorTo(Double x, Double step) { public static Double floorTo(Double x, Double step) {
if (x != 0d) { if (x != 0d) {
return Math.floor(x / step) * step; return Math.floor(x / step) * step;

View file

@ -12,9 +12,16 @@ public class RoundTest {
@Test @Test
public void roundToTest() throws Exception { public void roundToTest() throws Exception {
assertEquals( 0.55d, Round.roundTo(0.54d, 0.05d), 0.00000001d ); assertEquals( 0.55d, Round.roundTo(0.54d, 0.05d), 0.00000000000000000001d );
assertEquals( 1d, Round.roundTo(1.49d, 1d), 0.00000001d ); assertEquals( -3.26d, Round.roundTo(-3.2553715764602713d, 0.01d), 0.00000000000000000001d );
assertEquals( 0d, Round.roundTo(0d, 1d), 0.00000001d ); assertEquals( 0.816d, Round.roundTo(0.8156666666666667d, 0.001d), 0.00000000000000000001d );
assertEquals( 0.235d, Round.roundTo(0.235d, 0.001d), 0.00000000000000000001d );
assertEquals( 0.3d, Round.roundTo(0.3d, 0.1d), 0.00000000000000001d );
assertEquals( 0.0017d, Round.roundTo(0.0016960652144170627d, 0.0001d), 0.00000000000000000001d );
assertEquals( 0.0078d, Round.roundTo(0.007804436682291013d, 0.0001d), 0.00000000000000000001d );
assertEquals( 0.6d, Round.roundTo(0.6d, 0.05d), 0.00000000000000000001d );
assertEquals( 1d, Round.roundTo(1.49d, 1d), 0.00000000000000000001d );
assertEquals( 0d, Round.roundTo(0d, 1d), 0.00000000000000000001d );
} }
@Test @Test