1

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

Machavity
  • 30,841
  • 27
  • 92
  • 100
Hai Quach
  • 7
  • 5

1 Answers1

0

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.

Alien
  • 15,141
  • 6
  • 37
  • 57
  • It doesn't seem to be an issue with MathContext. If i print the result of division, the result is correct. I guess it is more about IBM JIT options. – Hai Quach Aug 13 '18 at 16:09