兩個float相減時丟失精度的解決方法
阿新 • • 發佈:2019-01-28
通常我們習慣這麼寫:
float a = 2.123f;
float b = 1.101f;
System.out.println("a-b=" + (a-b));
執行結果:a-b=1.022
那麼這麼寫呢?
a = 2.1235f;
b = 1.1012f;
System.out.println("a-b=" + (a-b));
執行結果:a-b=1.0223001
可我們的期望值是:a-b=1.0223
所以float的精度到了4位之後就得這麼寫:
BigDecimal c = new BigDecimal(Float.toString(a));
BigDecimal d = new BigDecimal(Float.toString(b));
System.out.println("a-b=" + (c.subtract(d)).floatValue());
執行結果:a-b=1.0223
============================================================================================
//兩個BigDecimal相加
big1 = big1.add(big2);
System.out.println(big1);
//兩個BigDecimal相減
big1 = big1.subtract(big2);
System.out.println(big1);
//兩個BigDecimal相乘
big1 = big1.multiply(big2);
System.out.println(big1);
//兩個BigDecimal相除
big1 = big1.divide(big2);
System.out.println(big1);