摘要
Java浮點數據類型在內存中存儲會出現精度丟失的情況,因此涉及浮點數據類型的計算需使用BigDecimal類及相關方法。
背景
前幾天遇到了一個浮點數精度處理的問題,簡單地說就是把String轉化為Double然后乘以精度,最后以int輸出,代碼如下:
public int getThreshInt(String thresh, int fractionDigits)
{
return (int) (Double.parseDouble(thresh) * Math.pow(10, fractionDigits));
}
經測試發現,當輸入為1.001時,輸出為1000??梢?,在該方法處理的過程中出現了精度丟失問題。
分析
為了進一步明確問題所在,測試代碼如下:
System.out.println(1.001 * 1);
System.out.println(1.001 * 10);
System.out.println(1.001 * 100);
System.out.println(1.001 * 1000);
System.out.println(1.001 * 10000);
輸出結果為
1.001
10.009999999999998
100.1
1000.9999999999999
10009.999999999998
由此可以確定:采用基本類型進行浮點數運算會出現精度丟失的情況。
解決方法
后經查閱相關資料發現,對于上述情況需借助BigDecimal類及相應方法,正確的解決步驟為:
1.調用BigDecimal(String)將基本類型轉化為BigDecimal類型;
2.采用BigDecimal的相關方法進行計算;
3.將結果轉化為以期望的數據類型輸出;
重寫該方法,代碼如下:
public int getThreshInt(String thresh, int fractionDigits)
{
return new BigDecimal(thresh).multiply(
new BigDecimal(Math.pow(10, fractionDigits))).intValue();
}