• 0

[Java] Double Multiplication


Question

In java when you multiply two doubles, often you won't get the result you were hoping for. For example 6*1.2 results in 7.19999... instead of 7.2.

Is there any way of sorting this out? You can round to 2 decimal places, I know, but what if the next multiplication needed 3 decimal places?

Thanks

Jether

Link to comment
https://www.neowin.net/forum/topic/607515-java-double-multiplication/
Share on other sites

2 answers to this question

Recommended Posts

  • 0

It's a fact of life with binary computers. It's not just Java, it's the hardware. 1.2 ie one-and-one-fifth can't be exactly represented as a binary fraction. You get close with one-and-an-eigth-and-a-sixteenth.... but never exactly one-fifth.

You have to chose when/where to round the result, depending on the application.

  • 0

Example: 7.199999... properly rounded to 3 decimal places = 7.200

7.199999... * 10^3 = 7199.999999...

7199.999999... + .5 = 7200.499999...

Math.floor(7200.499999...) / 10^3 = 7.200

Does it work for all values? Let's find out!

3.14159265 to 2 decimal places:

3.14159265 * 10^2 = 314.159265

314.159265 + .5 = 314.659265

Math.floor(314.659265) / 10^2 = 3.14

-3.14159265 to 4 decimal places:

-3.14159265 * 10^4 = -31415.9265

-31415.9265 - .5 = -31416.4265

Math.floor(-31416.4265) / 10^4 = -3.1416

The stuff behind it:

public class RoundDemo {
	public static void main (String[] args) {
		double x = 4.294967296;
		double y;
		System.out.println("xx);
		for (int decimal_places = 8; decimal_places >= 0; decimal_places--) {
			y = x * Math.pow(10, decimal_places);
			y += Math.signum(x) * .5;
			y = Math.floor(y) / Math.pow(10, decimal_places);
			String formatString = new String("y=%." + Integer.toString(decimal_places) + "f\n");
			System.out.printf(formatString, y);
		}
	}
}

That's how I usually do it. Why don't I use the Math.round() method instead of doing the rounding myself? The answer is simple:

System.out.println("Math.round(4.51)\t Math.round(4.51)); //5
System.out.println("Math.round(-4.51)\t Math.round(-4.51)); //-5
System.out.println("Math.round(-4.50)\t Math.round(-4.50)); //-4
System.out.println("Math.round(4.50)\t Math.round(4.50)); //5

Wow. It would appear that the rounding is not fair! It actually is fair. It just doesn't round the numbers as expected. Is it a floating point issue? Possibly. However, this simple illustration shows how bad rounding can be when a certain amount of precision is absolutely required, which is why I prefer to round numbers myself.

Edited by rpgfan
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.