Location>code7788 >text

Floating-point arithmetic in Java there are precision problems and solutions

Popularity:952 ℃/2024-09-27 20:42:32

Looking at the following piece of code, I'm sure children can see the answer at a glance, but is that the answer given by the computer?
public class TestDouble {
public static void main(String args[]) {
("0.05 + 0.01 = " + (0.05 + 0.01));
("1.0 - 0.42 = " + (1.0 - 0.42));
("4.015 * 100 = " + (4.015 * 100));
("123.3 / 100 = " + (123.3 / 100));
}

}
Complete run results:

I can't believe it, but the end result is a bunch of weird decimals.
SOLUTION: This is because because because floating point numbers are stored in binary form inside the computer, certain decimal decimals cannot be represented exactly. Therefore, direct arithmetic may lead to imprecise results.
cure
Three simple ways to handle this are given here
Method 1: Rounding
Rounding results using ()
Take the above code as an example for modification:
public class TestDouble { public static void main(String args[]) { ("0.05 + 0.01 = " + ((0.05 + 0.01)*100.0)/100.0); ("1.0 - 0.42 = " + ((1.0 - 0.42)*100.0)/100.0); ("4.015 * 100 = " + ((4.015 * 100)*100.0)/100.0); ("123.3 / 100 = " + ((123.3 / 100)*1000.0)/1000.0); } }
The results are shown below:

Note: Only integers are retained when used directly
Method 2: Use BigDecimal class
`import ;
import ;

public class BigDecimalRoundExample {

    public static void main(String[] args) {
        double num = 0.5 + 0.1;
        BigDecimal bd = new BigDecimal((num));
        BigDecimal x = (2, RoundingMode.HALF_UP);//2Indicates the number of decimal places to be retained

        (x);
    }
}

`
Results:
0.06