简体   繁体   中英

IBM java8 BigDecimal floating issue with MathContext.DECIMAL64

BigDecimal in IBM java 8 calculates incorrect value when adding floating decimal number with MathContext.DECIMAL64. Below is example code

MathContext context = MathContext.DECIMAL64;
BigDecimal p = BigDecimal.valueOf(0.05000);
BigDecimal test = p.divide(BigDecimal.valueOf(12), context);
System.out.println(test.add(BigDecimal.ONE, context));

The above code prints out as 1.000000000000000 instead of 1.004166666666666667

However, in the last line of code above, if I remove MathContext, it returns correct value as 1.004166666666666667.

NOTE: when debug the above code with the same JVM, in debug mode, the value is also 1.004166666666666667.

Question: Why does it cause the JVM returns different value with/without MathContext or in debug mode?

Tested with IBM JDK 1.6, 1.8 and Oracle JDK 1.8. Only experienced this issue with IBM JDK 1.8

IBM JDK 1.8 below has this issue

java version "1.8.0" Java(TM) SE Runtime Environment (build pwa6480sr3-20160428_01(SR3)) IBM J9 VM (build 2.8, JRE 1.8.0 Windows 7 amd64-64 Compressed References 20160427_301573 (JIT disabled, AOT disabled) J9VM - R28_Java8_SR3_20160427_1620_B301573 GC - R28_Java8_SR3_20160427_1620_B301573_CMPRSS J9CL - 20160427_301573) JCL - 20160421_01 based on Oracle jdk8u91-b14

I tried to use MathContext.DECIMAL128 . I saw code works fine. Tried to use it. I guess we have problem because bit size of for BigDecimal data.

NOTE: IF MathContext from 20 to up it works fine.

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