在逗号 Java 后将小数舍入到下一个 5 的乘法

Hot to round decimal to next multiplication of 5 after comma Java

我想得到最接近的十进制数。逗号后面的数字应该是5的乘法(逗号后面的2个数字),1-3向下舍入为0,4-6向下舍入为5,7-9向上舍入(递增)数字的左侧。如果是 0,也跳过第三个数字。

例如:

4.985 -> 5.0

4.37 -> 4.4

2.14 -> 2.15

4.41 -> 4.4

5.29 -> 5.3

4.17 -> 4.2

2.07 -> 2.1

4.64 -> 4.65

5.21 -> 5.2

2.34 -> 2.35

我已经试过了,但在一些测试中出错了。

public static void main(String[ ] args) {
    double[] check = {4.985, 4.37, 2.14, 4.41, 5.29, 4.17, 2.07, 6.64, 5.21, 2.34, 4.89};
    double[] results = {5.0, 4.4, 2.15, 4.4, 5.3, 4.2, 2.1, 6.65, 5.2, 2.35, 4.9};
    for(int i=0; i<check.length; i++){
        double res = getClosestValue(check[i]);
        System.out.println(check[i]+" should be "+results[i]+" got "+res+" so it is "+
                        assertEquals(res, results[i]));
    }
}

public static boolean assertEquals(double a, double b){
    return a==b;
}

public static double getClosestValue(double number) {
    String value = String.valueOf(number).substring(0, 4);
    int firstDigit = Character.getNumericValue(value.charAt(0));
    int secondDigit = Character.getNumericValue(value.charAt(2));
    int lastDigit = Character.getNumericValue(value.charAt(3));
    boolean secondChange = false;
    if (lastDigit <= 3) {
        lastDigit = 0;
    } else if (lastDigit >= 7) {
        lastDigit = 0;
        secondDigit++;
        secondChange = true;
    } else {
        lastDigit = 5;
    }
    if(secondChange){
        if(secondDigit <= 3){
            secondDigit = 0;
        } else if(secondDigit >= 7){
            secondDigit = 0;
            firstDigit++;
        }
    }
    String result = firstDigit + "." + secondDigit + (lastDigit != 0 ? lastDigit : "");
    return Double.parseDouble(result);
}

结果:

我的代码缺少什么?有没有更好的方法来获得这个?

编辑: 这与标记为重复的那个不重复,我试图在逗号后舍入 2 个数字,而不仅仅是 1 个数字

当最后一位大于或等于 7 且第二位小于 3 时,您的代码有意外输出。我检查您的期望 table。

根据您的意见,我认为您可以将相应的部分代码替换为以下代码:

if(secondChange){
    if (secondDigit == 10) {
        secondDigit = 0;
        firstDigit++;
    } 
}