-1

I don't know why java is rounding result. I used casting to float, I was adding '.0f'. Nothing want to work. I know that double is better for dividing but I don't need very precision result.

int A = Integer.parseInt(listBytesAnsw.get(2), 16); //ex. 18
int B = Integer.parseInt(listBytesAnsw.get(3), 16); //ex. 226
float rpm = (float) (A*255+B)/4; //Ans=1204 wrong, should be 1203.75

float rpm = (float) (A*255.0f+B)/4.0f; //dont work still 1204
GarryMoveOut
  • 377
  • 5
  • 19

1 Answers1

-1

The result you get is to be expected. After all:

255*226 = 4816
4816 / 4 = 1204

Of course, rounding and then casting would not work in case you have indeed a non-integer result. So look at the following code

System.out.println("(float)(7/4)=" + ((float)(7/4)));
System.out.println("(float)7/4=" + ((float)7/4));
System.out.println("(7+0.0f)/4=" + ((7+0.0f)/4));
System.out.println("7/(4+0.0f)=" + (7/(4+0.0f)));

results in

(float)(7/4)=1.0
(float)7/4=1.75
(7+0.0f)/4=1.75
7/(4+0.0f)=1.75

The first does not work as you found out. But either of the other solutions works.

luksch
  • 11,497
  • 6
  • 38
  • 53