Java:双舍入算法

Lig*_*228 1 java floating-point rounding

我对舍入算法感到好奇,因为在CS中我们必须模拟HP35而不使用数学库.我们在最终版本中没有包含舍入算法,但无论如何我想要这样做.

public class Round {
    public static void main(String[] args) {

        /*
         * Rounds by using modulus subtraction
         */
        double a = 1.123599;

        // Should you port this to another method, you can take this as a parameter
        int b = 5;

        double accuracy = Math.pow(10, -b);

        double remainder = a % accuracy;

        if (remainder >= 5 * accuracy / 10) // Divide by ten is important because remainder is smaller than accuracy
            a += accuracy;

        a -= remainder;


        /*
         * Removes round off error done by modulus
         */
        String string = Double.toString(a);

        int index = string.indexOf('.') + b;

        string = string.substring(0, index);

        a = Double.parseDouble(string);

        System.out.println(a);


    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个很好的算法,还是有更好的算法?我不关心Java API中定义的那些,我只是想知道它是如何完成的.

[编辑]这是我在查看EJP答案后提出的代码

public class Round {
    public static void main(String[] args) {

        double a = -1.1234599;
        int b = 5;
        boolean negative = a < 0;

        if (negative) a = -a;

        String string = Double.toString(a);
        char array[] = string.toCharArray();

        int index = string.indexOf('.') + b;
        int i = index;

        int value;
        if (Character.getNumericValue(array[index +1]) >= 5) {

            for (; i > 0; i--) {
                value = Character.getNumericValue(array[i]);

                if (value != -1) {
                    ++value;
                    String temp = Integer.toString(value)
                    array[i] = temp.charAt(temp.length()-1);
                    if (value <= 9) break;
                }
            }
        }

        string = "";
        for (int j=0; j < index + 1 ; j++) {
            string += array[j];
        }

        a = Double.parseDouble(string);

        if (negative) a =-a;

        System.out.println(a);
    }
}
Run Code Online (Sandbox Code Playgroud)

use*_*421 5

浮点数没有小数位.他们有二进制位置,这两者是不可比的.任何修改浮点变量以具有特定小数位数的尝试都注定要失败.

转换为十进制基数后,必须将舍入到指定的小数位数.