Rounding to 2 decimals with the math method

Viewed 45

So I'm working on an assignment where I'm supposed to do a table with different values etc. But I have run into a problem where the (charging time/laddningstid(h)) round up to 16.0 when I want it so say 15.57. Since 35.8/2.3 = 15.57.

So my question is what have I done wrong here? How can I make it say the correct value instead of 16.0

CODE:

class Main {
  public static void main(String[] args) {

    double batteryEffect = 35.8;
    int current = 10;
    int current1 = 16;
    int current2 = 32;

    int voltage = 230;
    int voltage1 = 400;

    
    double calcEffect = 0;

    int noOfDecimals = 2;
    double scale = 0;
    scale = Math.pow(10, noOfDecimals);
    calcEffect = Math.round(current*voltage)*scale/scale/1000;

    
    double calcCharge = 0;

    calcCharge = Math.round(batteryEffect/calcEffect)*scale/scale;
    

    System.out.print("Batteri" + " " + batteryEffect + "(kWh)");
    System.out.print("\n");
    System.out.print("\nStröm(A)\tSpänning(V)\tLaddeffekt(kW)\tLaddningstid(h)");  
    System.out.print("\n=======================================================");
    System.out.print("\n");
    System.out.print(current + "\t\t\t" + voltage + "\t\t\t"  + calcEffect + "\t\t\t\t" + calcCharge);
    System.out.print("\n");
    System.out.print(current1 + "\t\t\t" + voltage);
  }
}

EDIT: My bad I didn't know the picture was gonna get that small first time posting here.

1 Answers

The Math.round function rounds its argument to the nearest integer, so it is expected that it rounds 15.57 to 16.

If you want to limit to number of digits after the decimal point, you can use calcCharge.toFixed(2) (without the Math.round). Or you can do Math.round(calcCharge * 100) / 100.

Related