简体   繁体   中英

Java: double rounding algorithm

I got curious about a rounding algorithm, because in CS we had to emulate an HP35 without using the Math library. We didn't include a rounding algorithm in our final build, but I wanted to do it anyway.

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


    }
}

Is this a good algorithm, or are there any better ones? I don't care about the ones defined in the Java API, I just wanted to know how it was done.

[EDIT] Here's the code I came up with after looking over EJP's answer

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);
    }
}

Floating-point numbers don't have decimal places. They have binary places, and the two are not commensurable. Any attempt to modify a floating-point variable to have a specific number of decimal places is doomed to failure.

You have to do the rounding to a specified number of decimal places after conversion to a decimal radix.

There are a different ways to round numbers. The RoundingMode documentation for Java (introduced in 1.5) should give you a brief introduction to the different methods people use.

I know you said you don't have access to the Math functions, but the simplest rounding you can do is:

public static double round(double d)
{
    return Math.floor(d + 0.5);
}

If you don't want to use any Math functions, you could try something like this:

public static double round(double d)
{
    return (long)(d + 0.5);
}

Those two probably behave differently in some situations (negative numbers?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM