Skip to content Skip to sidebar Skip to footer

Multiplication Error

If I multiply 12 x 25.4 i get 304.7 whereas I expect 304.8. I see that using odd numbers x 25.4 I get the correct answers but using even numbers always seem to be off by 0.1. I a

Solution 1:

Floating point number types in Java are approximations. Try adding 1 + 2 + 3 + 4 as float type and you might end up with 10.00000003.

To ensure accurate math, try using the java.math.BigDecimal type. It is a memory hog, but is accurate.

Solution 2:

I don't know what programming language you're using, but 12 * 25.4 gives me 304.8 when I do this using Java:

publicstaticvoidmain(String[] args){
   double result = 12 * 25.4;

   System.out.printf("Result: %.1f%n", result );
}

But seriously -- how are you displaying the result obtained? Are you using one of the many numeric formatting options available in Java (one of which is displayed above)? Also do you understand the limits to precision when using 64-bit IEEE 754 floating point (double) variables? They are pretty accurate and useful for most floating-point applications, but not applications that have strict precision requirements such as financial calculations.

Post a Comment for "Multiplication Error"