From e350c8c3c3e3e646c6f14471cee3ff98166e24c9 Mon Sep 17 00:00:00 2001 From: Wouter Lagerweij Date: Sun, 17 Sep 2017 00:53:16 +0200 Subject: [PATCH] Rounding fix --- .../java/info/nightscout/utils/Round.java | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/utils/Round.java b/app/src/main/java/info/nightscout/utils/Round.java index 26a4d5abce..d8bc76502b 100644 --- a/app/src/main/java/info/nightscout/utils/Round.java +++ b/app/src/main/java/info/nightscout/utils/Round.java @@ -1,15 +1,42 @@ package info.nightscout.utils; +import android.support.annotation.NonNull; +import android.util.Log; + +import java.math.BigDecimal; + /** * Created by mike on 20.06.2016. */ public class Round { - public static Double roundTo(double x, Double step) { + public static Double roundTo(Double x, Double step) { + + if (step > 1) { + return roundToWhole(x, step); + } else { + return roundToNrOfDecimals(x, getDecimalsFromStep(step)); + } + } + + private static int getDecimalsFromStep(Double step) { + String stepString = Double.toString(step); + return stepString.substring(stepString.indexOf('.') + 1).length(); + } + + private static Double roundToNrOfDecimals(Double x, int decimals) { + BigDecimal number = new BigDecimal(Double.toString(x)); + number = number.setScale(decimals, BigDecimal.ROUND_HALF_UP); + + return number.doubleValue(); + } + + private static Double roundToWhole(Double x, Double step) { if (x != 0d) { return Math.round(x / step) * step; } return 0d; } + public static Double floorTo(Double x, Double step) { if (x != 0d) { return Math.floor(x / step) * step;