Search code examples
javamathrounding-error

Trying to use Math.floor to round numbers but it doesn't cut them off at the right point


I am trying to use Math.floor to round a quotient to 1, 2, and 3 places but it wont cut the numbers off at the right place

Scanner input = new Scanner(System.in);
    double x;
    double y;


    System.out.println("Enter 2 values seperated by a space, x and y to enter into the eqation: (x/y).");
    x = input.nextDouble();
    y = input.nextDouble();

    for(int i = 1; i < 4.0; i++){
        double z = Math.floor((x/y)* (10^i) + 0.5) / (10^i);
        System.out.println(z);

    }

Here is one of the outputs: https://i.sstatic.net/OBod0.jpg


Solution

  • You need to use Math.pow(10, i), because ^ is a bitwise operator:

    double z = Math.floor((x/y)* Math.pow(10,i) + 0.5) / Math.pow(10,i);