關於BigDecimal轉String的准確性問題


case 1:

String str=new BigDecimal(123.9).toString()

輸出str:123.900000000000005684341886080801486968994140625

解決方案:

String str=BigDecimal.valueOf(123.9).toString()

 

 

case2:

//數據庫中該字段類型為decimal(20, 2),值為200.10
BigDecimal num = testMapper.query();
//值為200.1
String str = testDTO.getNum();
//比較BigDecimal與String:
if (num != null) {
    boolean ifEquals = num.toString.equals(str);
}            

結果為:false

解決方案:比較兩個BigDecimal要通過BigDecimal的compareTo()方法。

 

 

case3:

不要直接比較double、float類型的值,因為他們可能是不准確的。建議轉成BigDecimal進行比較,String也不建議,因為如3.14 != 3.140。另外,數字后f、d表示float與double,也就意味着他們的精度是不同的:

    public static void main(String[] args) {
        double a = 3.14f;
        double b = 3.14;
        System.out.println(a == 3.14);
        System.out.println(b == 3.14);
        System.out.println(a);
        System.out.println(b);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM