3

Possible Duplicate:
Floating point inaccuracy examples

When using the modulo operator in java I'm not getting the number I expect to get.

Heres what I'm doing:

double input = 5.59;
System.out.println("Output: " + (input % 2));

I expect to see 1.59 as the result however it is printing out 1.5899999999999999. Any clue as to why this may be?

Community
  • 1
  • 1
Matt Langlois
  • 305
  • 3
  • 17
  • This comes from floating point inaccuracy, [here is a great SO answer explaining exactly what is happening.](http://stackoverflow.com/a/2100502/874257) – Josiah Hester Oct 09 '12 at 17:38
  • 1
    Ok, this is a multi multi duplicate (IEEE754, float, etc.). Let us a minute to find it... – Denys Séguret Oct 09 '12 at 17:39
  • Another similar question : http://stackoverflow.com/questions/1661273/floating-point-arithmetic-not-producing-exact-results-in-java with answers which may help you – Denys Séguret Oct 09 '12 at 17:41
  • Thanks @JosiahHester I'll read up on it. Do oyu know a way I may be able to fix this. I need it for a make change program for my grade 11 programming class. It is supposed to convert a number to exact change. – Matt Langlois Oct 09 '12 at 17:41

2 Answers2

5

This comes from floating point inaccuracy, here is a great SO answer explaining exactly what is happening.

If you want it to round out the number you need to use formatting like this:

double input = 5.59;
System.out.format("Output: %.2f%n", (input % 2));
  • The "%" tells the formatter to replace itself with the first numeric argument. You can add as many of these as you want.
  • The ".2" tells the formatter to format the number with two places after the decimal.
  • The "f" just tells the formatter it is a floating point number.
  • The "%n" is a new line character appropriate to the platform running the application. You should always use "%n", rather than "\n".

Here is some good documentation for all this.

Hope this helps!

Community
  • 1
  • 1
Josiah Hester
  • 6,065
  • 1
  • 24
  • 37
1

Its because of precision of Double. You need to format it to achieve your desired output.

double input = 5.59;
System.out.println("Output: " + new DecimalFormat("00.00").format(input % 2));

It will print Output: 1.59

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103