0

I'm trying to learn java for AP computer science A and thought I would try to make a simple remainder calculator. This calculator prompts the user to enter a number and it will give the remainder when divided by 1 (it's not a good calculator).

Here is my program:

public class Unit2Lab2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        float Value = scanner.nextFloat();
        float a = Value % 1;
        System.out.println(a);
    }
}

It was all fine and dandy but when I tested it out by plugging in the value of 15.98, the result I got was 0.999999976. I don't know why this happened but I managed to circumvent the issue by using the df.format command I found online.

I still want to know if there is a way to stop the remainder function from getting wonky.

rjames
  • 15
  • 3
  • 2
    See https://stackoverflow.com/questions/588004/is-floating-point-math-broken – user Jul 07 '20 at 18:43
  • check your results. When I run your program I get .97999954 which is as close as we can get to representing .98. Remember that your computer operates in binary. if you need more help understanding this let me know and I'll provide an example. – DCR Jul 07 '20 at 18:50
  • I understand why it happens but what I don't know is whether or not the is a way to go around this. I know that using the df.format(); command will do this but it could only be used when it is in a print command. I guess what I'm trying to ask is whether there is a command that can be used in a variable initialization line. For example, in the original question, we defined "a" as the remainder but is there a command that can be used like "float b = command(a)" – rjames Jul 08 '20 at 19:51

0 Answers0