Home > Java > javaTutorial > How to Avoid Precision Errors in Java Double Arithmetic?

How to Avoid Precision Errors in Java Double Arithmetic?

Susan Sarandon
Release: 2024-12-10 00:38:08
Original
332 people have browsed it

How to Avoid Precision Errors in Java Double Arithmetic?

How to Eliminate Precision Issues with Java Double Arithmetic

In certain scenarios, floating point arithmetic in Java can lead to unexpected rounding issues, such as in the subtraction example provided:

double tempCommission = targetPremium.doubleValue()*rate.doubleValue()/100d;
double netToCompany = targetPremium.doubleValue() - tempCommission;
double dCommission = request.getPremium().doubleValue() - netToCompany;
Copy after login

Here, the desired result for dCommission is 877.85, but it is instead calculated as 877.8499999999999. This discrepancy arises due to precision limitations in floating point arithmetic.

To resolve this issue, the optimal solution is to utilize the java.math.BigDecimal class. BigDecimal offers precise calculations and effectively controls the precision of floating point arithmetic. Here's how you can implement it in the given example:

import java.math.BigDecimal;

BigDecimal premium = BigDecimal.valueOf("1586.6");
BigDecimal netToCompany = BigDecimal.valueOf("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);
Copy after login

This code results in the desired output:

877.85 = 1586.6 - 708.75
Copy after login

By employing BigDecimal, you ensure accurate calculations without compromising precision.

The above is the detailed content of How to Avoid Precision Errors in Java Double Arithmetic?. 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