Multiply two numbers exactly in Java

I was looking for the exact way to multiply two floating point numbers in Java, and I read that I should use BigDecimal, however it does not work properly. What am I doing wrong?

My code is:

BigDecimal a = new BigDecimal(3.53); BigDecimal b = new BigDecimal(3.59); BigDecimal c = a.multiply(b); System.out.println(c); 

Result:

 12.672699999999998796873512674210388041622697702955394242845497954075284496866515837609767913818359375 

Expected Result:

 12.6727 
+1
source share
1 answer

When you use the constructor BigDecimal(double) , it cannot be more accurate than double , use the String form instead. How,

 BigDecimal a = new BigDecimal("3.53"); BigDecimal b = new BigDecimal("3.59"); BigDecimal c = a.multiply(b); System.out.println(c); 

What are the exits

 12.6727 

Associated Javadoc says partially -

Notes:

  • The results of this constructor may be somewhat unpredictable. It can be assumed that writing a new BigDecimal(0.1) in Java creates a BigDecimal value that is exactly 0.1 (an unscaled value of 1 with a scale of 1), but in fact it is 0.1000000000000000055511151231257827021181583404541015625 . This is because 0.1 cannot be represented exactly as double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is passed to the constructor is not exactly 0.1, regardless of what happens.

  • The String constructor, on the other hand, is quite predictable: writing new BigDecimal("0.1") creates a BigDecimal, which is exactly 0.1, as you would expect. Therefore, it is recommended that the string constructor be used in preference to this.

+12
source

All Articles