简体   繁体   中英

Is there any condition where Bigdecimal with MathContext.DECIMAL32 does not provides correct result?

System.out.println("Result="+new BigDecimal(((63.19* 15) + (63.37* 5))).divide(new BigDecimal(15 + 5), MathContext.DECIMAL64).doubleValue());

Result=63.23499999999999

But with MathContext.DECIMAL32 we are getting correct result, see below:

System.out.println("Result="+new BigDecimal(((63.19* 15) + (63.37* 5))).divide(new BigDecimal(15 + 5), MathContext.DECIMAL32).doubleValue());

Result=63.235

The problem here not BigDecimal , but the fact that (63.19* 15) + (63.37* 5) is not 1264.7 but 1264.6999999999998 , because the former cannot be represented as a double .

If you do

new BigDecimal("1264.7").divide(new BigDecimal("20"), MathContext.DECIMAL64)

instead, you get the desired result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM