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

How to Avoid Precision Errors in Java Double Arithmetic?

Susan Sarandon
Susan SarandonOriginal
2024-12-10 00:38:08277browse

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;

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

This code results in the desired output:

877.85 = 1586.6 - 708.75

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!

Statement:
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