1. 程式人生 > >java中四捨五入——double轉BigDecimal的精度損失問題

java中四捨五入——double轉BigDecimal的精度損失問題

背景

     在部落格 噁心的0.5四捨五入問題 一文中看到一個關於 0.5 不能正確的四捨五入的問題。主要說的是 double 轉換到 BigDecimal 後,進行四捨五入得不到正確的結果:

複製程式碼
public class BigDecimalTest {
    public static void main(String[] args){
        double d = 301353.05;
        BigDecimal decimal = new BigDecimal(d);
        System.out.println(decimal);//301353.0499999999883584678173065185546875
System.out.println(decimal.setScale(1, RoundingMode.HALF_UP));//301353.0 } }
複製程式碼

輸出的結果為:

301353.0499999999883584678173065185546875
301353.0

這個結果顯然不是我們所期望的,我們希望的是得到 301353.1 。

原因

     允許明眼人一眼就看出另外問題所在——BigDecimal的建構函式 public BigDecimal(double val) 損失了double 引數的精度,最後才導致了錯誤的結果。所以問題的關鍵是:BigDecimal的建構函式 public BigDecimal(double val) 損失了double 引數的精度。

解決之道

因為上面找到了原因,所以也就很好解決了。只要防止了 double 到 BigDecimal 的精度的損失,也就不會出現問題。

1)很容易想到第一個解決辦法:使用BigDecimal的以String為引數的建構函式:public BigDecimal(String val)  來替代。

複製程式碼
public class BigDecimalTest {
    public static void main(String[] args){
        double d = 301353.05;
        System.out.println(new BigDecimal(new
Double(d).toString())); System.out.println(new BigDecimal("301353.05")); System.out.println(new BigDecimal("301353.895898895455898954895989")); } }
複製程式碼

輸出結果:

301353.05
301353.05
301353.895898895455898954895989

我們看到了沒有任何的精度損失,四捨五入也就肯定不會出錯了。

2)BigDecimal的建構函式 public BigDecimal(double val) 會損失了double 引數的精度,這個也許應該可以算作是 JDK 中的一個 bug 了。既然存在bug,那麼我們就應該解決它。上面的辦法是繞過了它。現在我們實現自己的 double 到 BigDecimal 的轉換,並且保證在某些情況下可以完全不損失 double 的精度。

複製程式碼
import java.math.BigDecimal;

public class BigDecimalUtil {
    
    public static BigDecimal doubleToBigDecimal(double d){
        String doubleStr = String.valueOf(d);
        if(doubleStr.indexOf(".") != -1){
            int pointLen = doubleStr.replaceAll("\\d+\\.", "").length();    // 取得小數點後的數字的位數
            pointLen = pointLen > 16 ? 16 : pointLen;    // double最大有效小數點後的位數為16
            double pow = Math.pow(10, pointLen);
       long tmp = (long)(d * pow);
            return new BigDecimal(tmp).divide(new BigDecimal(pow));
        }
        return new BigDecimal(d);
    }
    
    public static void main(String[] args){
//        System.out.println(doubleToBigDecimal(301353.05));
//        System.out.println(doubleToBigDecimal(-301353.05));
//        System.out.println(doubleToBigDecimal(new Double(-301353.05)));
//        System.out.println(doubleToBigDecimal(301353));
//        System.out.println(doubleToBigDecimal(new Double(-301353)));
        
        double d = 301353.05;//5898895455898954895989;
        System.out.println(doubleToBigDecimal(d));
        System.out.println(d);
        System.out.println(new Double(d).toString());
        System.out.println(new BigDecimal(new Double(d).toString()));
        System.out.println(new BigDecimal(d));
    }
}
複製程式碼

輸出結果:

301353.05
301353.05
301353.05
301353.05
301353.0499999999883584678173065185546875

上面我們自己寫了一個工具類,實現了 double 到 BigDecimal 的“無損失”double精度的轉換。方法是將小數點後有有效數字的double先轉換到小數點後沒有有效數字的double,然後在轉換到 BigDecimal ,之後使用BigDecimal的 divide 返回之前的大小。

上面的結果看起來好像十分的完美,但是其實是存在問題的。上面我們也說到了“某些情況下可以完全不損失 double 的精度”,我們先看一個例子:

複製程式碼
    public static void main(String[] args){
        double d = 301353.05;
        System.out.println(doubleToBigDecimal(d));
        System.out.println(d);
        System.out.println(new Double(d).toString());
        System.out.println(new BigDecimal(new Double(d).toString()));
        System.out.println(new BigDecimal(d));
        
        System.out.println("=========================");
        d = 301353.895898895455898954895989;
        System.out.println(doubleToBigDecimal(d));
        System.out.println(d);
        System.out.println(new Double(d).toString());
        System.out.println(new BigDecimal(new Double(d).toString()));
        System.out.println(new BigDecimal(d));
        System.out.println(new BigDecimal("301353.895898895455898954895989"));
        
        System.out.println("=========================");
        d = 301353.46899434;
        System.out.println(doubleToBigDecimal(d));
        System.out.println(d);
        System.out.println(new Double(d).toString());
        System.out.println(new BigDecimal(new Double(d).toString()));
        System.out.println(new BigDecimal(d));
        
        System.out.println("=========================");
        d = 301353.45789666;
        System.out.println(doubleToBigDecimal(d));
        System.out.println(d);
        System.out.println(new Double(d).toString());
        System.out.println(new BigDecimal(new Double(d).toString()));
        System.out.println(new BigDecimal(d));
    }
複製程式碼

輸出結果:

301353.05
301353.05
301353.05
301353.05
301353.0499999999883584678173065185546875
=========================
301353.89589889544
301353.89589889545
301353.89589889545
301353.89589889545
301353.895898895454593002796173095703125
301353.895898895455898954895989
=========================
301353.46899434
301353.46899434
301353.46899434
301353.46899434
301353.4689943399862386286258697509765625
=========================
301353.45789666
301353.45789666
301353.45789666
301353.45789666
301353.4578966600238345563411712646484375
我們可以看到:我們自己實現的 doubleToBigDecimal 方法只有在 double 的小數點後的數字位數比較少時(比如只有5,6位),才能保證完全的不損失精度

在 double 的小數點後的數字位數比較多時,d * pow 會存在精度損失,所以最終的結果也會存在精度損失。所以如果小數點後的位數比較多時,還是使用 BigDecimal的 String 引數的建構函式為好,只有在小數點後的位數比較少時,才可以採用自己實現的 doubleToBigDecimal 方法。

因為我們看到原始的double的轉換之後的BigDecimal的數字的最後一位一個時5,一個是4,原因是在上面的轉換方法中:

long tmp = (long)(d * pow);

這一步可能存在很小的精度損失,因為 d 是一個 double ,d * pow 之後還是一個 double(但是小數點之後都是0了,所以到long的轉換沒有精度損失) ,所以會存在很小的精度損失(double的計算總是有可能存在精度損失的)。但是這個精度損失和 BigDecimal的建構函式 public BigDecimal(double val) 的精度損失相比而言,不會顯得那麼的突兀(也許我們自己寫的doubleToBigDecimal也是存在問題的,歡迎指點)。

總結

如果需要保證精度,最好是不要使用BigDecimal的double引數的建構函式,因為存在損失double引數精度的可能,最好是使用BigDecimal的String引數的建構函式。最好是杜絕使用BigDecimal的double引數的建構函式。

後記:

     其實說這是BigDecimal的一個bug,有標題黨的嫌疑,最多可以算作是BigDecimal的一個“坑”。