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?
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));
Here is some good documentation for all this.
Hope this helps!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With