Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing float values in Java

Look at the three lines of code below.

  float f = 1;

  float g = 1.1;

  float h = 1.1f;

Second line has compilation errors, while the other lines do not have compilation errors. First line is working fine without suffix f and third line is working with suffix f. Why is this?

like image 659
Abhishek Jain Avatar asked Jun 13 '10 17:06

Abhishek Jain


1 Answers

First line automatically casts int to float (ok).

Second line could not cast double to float because of loss of precision. You can make an explicit cast:

float g = (float) 1.1;

Third line does not need modification.

like image 171
Arne Deutsch Avatar answered Oct 15 '22 08:10

Arne Deutsch