1

I have a method that calculates the average

Note class:

private Double moyenneFinale;

@Column(name = "moyenne_finale")
public Double getMoyenneFinale() {
    return this.moyenneFinale;
}

public void setMoyenneFinale(Double moyenneFinale) {
    this.moyenneFinale = moyenneFinale;
}

Class calBean

private double result;
public double moyenneFinale;
public calNote {
    result=0.0
    result= ((100 * 20)/100)/45;
    moyenneFinale=result;
    note.setMoyenneFinale(moyenneFinale);
}
//getter and setter

the result should be 0.44 but recorded in the database given value is 0.0 if I make +1 it will be 1.0

Alexey Malev
  • 6,408
  • 4
  • 34
  • 52
GR Seif
  • 49
  • 1
  • 9
  • possible duplicate of [Division of integers in Java](http://stackoverflow.com/questions/7220681/division-of-integers-in-java) – BackSlash May 07 '14 at 10:13
  • @BackSlash The question may be a duplicate but not exactly of the question you linked since this question adds the nuance of operands being literals and their type being changed by adding a `.0` to them. – Pablo Francisco Pérez Hidalgo May 07 '14 at 10:30

2 Answers2

2

All the numeric literals at ((100 * 20)/100)/45 are integers so each operation performs integer arithmetic instead floating pointer arithmetic and finally the result is cast to double at the assignation operation.

You should change at least one of your literals to 100.0, 20.0, 45.0, ...

1

In line

result= ((100 * 20)/100)/45;

you are using operator / on integers. When used on integers, operator / behaves as "DIV" (resulting integer). Examples: 10/4=2, but 10.0/4=2.5, 10/4.0=2.5, 10.0/4.0=2.5.

Options are:

To set numbers as 100.0, 20.0, 100.0 and 45.0. (It is enough to set just first one to 100.0).

result= ((100.0 * 20)/100)/45;

To use casting on numbers. (double)100.

result= (((double)100 * 20)/100)/45;

Or to add 1.0* before equation;

result= 1.0*((100 * 20)/100)/45;

Tho, first method is best in your case, second and third are useful if you are given integers x, y, z, t and your result is ((x * y)/z)/t;

Rod
  • 49
  • 3