I’m making a calculation module about that accepts double or BigDecimal like this but I have this problem.
double x = 2.3333333333312398;
BigDecimal big = BigDecimal.valueOf(2.3333333333312398);
I print their values
System.out.println(x);
System.out.println(big);
and the output
2.3333333333312396
2.3333333333312396
I tried to changed the value of x and big variable to 2.3333333333312395
but the output still the same. I changed it again to 2.3333333333312396 and prints the same value.
If I changed again to 2.3333333333312394 the displayed again the weird value
2.3333333333312396
What’s the cause of this problem? Thanks!
You’re running up against double’s limits to accuracy since you’re initializing your BigDecimal with a double literal. Instead, consider initializing your BigDecimal with a String literal, not a double literal value:
which returns: