Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Modulo operator [duplicate]

Tags:

java

modulo

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?

like image 439
Matt Langlois Avatar asked Mar 31 '26 07:03

Matt Langlois


2 Answers

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!

like image 139
Josiah Hester Avatar answered Apr 02 '26 20:04

Josiah Hester


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

like image 33
Subhrajyoti Majumder Avatar answered Apr 02 '26 21:04

Subhrajyoti Majumder