浮點數運算出現誤差的解決方案
阿新 • • 發佈:2018-12-03
直接上程式碼
public static void main(String[] args){
Double a = 7.77;
Double b = 3.33;
System.out.println(a-b);
System.out.println(new BigDecimal(a.toString()).subtract(new BigDecimal(b.toString())));
}
輸出結果
4.4399999999999995
4.44
使用BigDecimal承載資料的型別最好是String型別,否則依然會出現誤差
同時附上加減乘除的方法
public static void main(String[] args){ Double a = 7.77; Double b = 3.33; System.out.println(a-b); //加 System.out.println(new BigDecimal(a.toString()).subtract(new BigDecimal(b.toString()))); //減 System.out.println(new BigDecimal(a.toString()).add(new BigDecimal(b.toString()))); //乘 System.out.println(new BigDecimal(a.toString()).multiply(new BigDecimal(b.toString()))); //除 ///System.out.println(new BigDecimal(a.toString()).divide(new BigDecimal(b.toString()))); System.out.println(new BigDecimal(a.toString()).divide(new BigDecimal(b.toString()),BigDecimal.ROUND_HALF_DOWN)); }
注意在使用除法的時候,要指定舍入模式,否則在除不盡的情況下會報"Non-terminating decimal expansion; no exact representable decimal result"異常