Home > Java > javaTutorial > How to Avoid Floating Point Precision Errors in Java: Floats, Doubles, and BigDecimal

How to Avoid Floating Point Precision Errors in Java: Floats, Doubles, and BigDecimal

Susan Sarandon
Release: 2024-11-18 04:43:02
Original
845 people have browsed it

How to Avoid Floating Point Precision Errors in Java: Floats, Doubles, and BigDecimal

Avoiding Floating Point Precision Errors with Floats and Doubles in Java

When working with large sums of floats or doubles in Java, accumulating floating point precision errors can be an issue. This error arises due to the inability of floats or doubles to precisely represent certain numerical values, such as 0.1.

Consider the following code:

for (float value = 0.0f; value < 1.0f; value += 0.1f) {
    System.out.println(value);
}
Copy after login

Expected output:

0.1
0.2
0.3
...
0.9
Copy after login
Copy after login

Actual output:

0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.70000005
0.8000001
0.9000001
Copy after login

As evident, the output deviates from the expected values due to floating point inaccuracies. To resolve this issue, there are two primary approaches:

1. Adjust Display Precision and Allow Tolerances

When using the double type, limit the display to the required number of digits and introduce a small tolerance for equality checks. This allows for the representation of numbers such as 0.1 without significant rounding errors.

2. Use BigDecimal for Precise Representation

Alternatively, consider using BigDecimal instead of floats or doubles. BigDecimal provides a way to represent numbers with arbitrary precision, eliminating rounding errors and allowing for exact representation of values like 0.1.

Below is an example utilizing BigDecimal:

BigDecimal step = new BigDecimal("0.1");
for (BigDecimal value = BigDecimal.ZERO;
     value.compareTo(BigDecimal.ONE) < 0;
     value = value.add(step)) {
    System.out.println(value);
}
Copy after login

This code will print:

0.1
0.2
0.3
...
0.9
Copy after login
Copy after login

By choosing the appropriate approach, developers can effectively minimize or eliminate floating point precision errors when working with floats or doubles in Java.

The above is the detailed content of How to Avoid Floating Point Precision Errors in Java: Floats, Doubles, and BigDecimal. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template