Java用BigDecimal解決double類型相減時可能存在的誤差
double類型的兩個數相減可能存在誤差,比如System.out.println(2099 - 1999.9);的結果為99.09999999999991
可以用BigDecimal解決:
public class TestDouble {
//兩個Double數相減
public static Double sub(Double d1, Double d2) {
if (d1 == null || d2 == null) {
return null;
}
BigDecimal b1 = new BigDecimal(d1.toString());
BigDecimal b2 = new BigDecimal(d2.toString());
return b1.subtract(b2).doubleValue();
}
//兩個Double數相加
public static Double add(Double d1, Double d2) {
if (d1 == null || d2 == null) {
return null;
}
BigDecimal b1 = new BigDecimal(d1.toString());
BigDecimal b2 = new BigDecimal(d2.toString());
return b1.add(b2).doubleValue();
}
//兩個Double數相除,并保留scale位小數
public static Double div(Double d1, Double d2, int scale) {
if (d1 == null || d2 == null || scale < 0) {
return null;
}
BigDecimal b1 = new BigDecimal(d1.toString());
BigDecimal b2 = new BigDecimal(d2.toString());
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
// 兩個Double數相乘
public static Double mul(Double d1, Double d2) {
if (d1 == null || d2 == null) {
return null;
}
BigDecimal b1 = new BigDecimal(d1.toString());
BigDecimal b2 = new BigDecimal(d2.toString());
return b1.multiply(b2).doubleValue();
}
/**
* 遇到.5的情況時往上近似
*
* @param d
* @param scale
* @return
*/
public static Double setDoubleScale(Double d, int scale) {
if (d == null || scale < 0) {
return null;
}
BigDecimal b = new BigDecimal(d);
return b.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static void main(String[] args) {
Double d1 = 2099d;
Double d2 = 1999.999;
System.out.println(d1 - d2);
System.out.println(sub(d1, d2));
System.out.println("------------------------------------");
System.out.println(d1 * d2);
System.out.println(mul(d1, d2));
System.out.println("------------------------------------");
System.out.println(d1/d2);
System.out.println(div(d1,d2,4));
}
}
結果:
99.00099999999998
99.001
------------------------------------
4197997.901
4197997.901
------------------------------------
1.0495005247502625
1.0495
到此這篇關于Java用BigDecimal解決double類型相減時可能存在的誤差的文章就介紹到這了,更多相關Java double相減誤差內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring gateway + Oauth2實現單點登錄及詳細配置
gateway是基于 WebFlux的響應式編程框架,所以在使用securityConfig時采用的注解是@EnableWebFluxSecurity,接下來通過本文給大家介紹Spring gateway + Oauth2實現單點登錄及詳細配置,感興趣的朋友一起看看吧2021-09-09
Spring Boot 自定義 Shiro 過濾器無法使用 @Autowired問題及解決方法
這篇文章主要介紹了Spring Boot 自定義 Shiro 過濾器無法使用 @Autowired問題及解決方法 ,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06
解決idea找不到類could not find artifact問題
本文總結了解決Java項目中找不到類的問題的常見解決方案,包括刷新Maven項目、清理IDEA緩存、Maven Clean Install、重新Package、解決依賴沖突和手動導入依賴包等方法2025-01-01

