Java:双舍入算法

标签 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);


    }
}

这是一个好的算法,还是有更好的算法?我不关心 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);
    }
}

最佳答案

float 没有小数位。它们有二元的地方,两者不可比。任何将浮点变量修改为具有特定小数位数的尝试都注定要失败。

转换为十进制基数后,您必须四舍五入到指定的小数位数。

关于Java:双舍入算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30114111/

相关文章:

c# - Math.Round for decimal

java - BigDecimal 的奇怪舍入问题

Javax.validation - 如何使用指定日期验证日期属性

string - 如何将二进制字符串转换为整数或 float ?

java - 如何与 webdriver 中的 List<WebElement> 进行比较?

在C中将int数组更改为float数组

c - jeo=(1/(1+decade));没有给我准确的答案

SQL Server ROUND() 不适用于以 1 结尾的 FLOAT

java - 直接在客户端处理接收到的消息(通过 netty 框架使用 nio)

java - 无法从 Java 中的命令行参数将值压入堆栈