0

why do I get this error message when i try to compile the following code?

float a = 1/0.1;
System.out.println(a);

or

float b = 1/0.002;
System.out.println(b);

incompatible types: possible lossy conversion from double to float

Am i getting an overflow? I'm looking to understand the theory behind this. Thanks in advance.

  • 3
    Because `0.1` and `0.002` are `double` literals. So you end up with `int/double` which results also in `double` value. Since you are trying to assigning that `double` value to `float` variable, there is a risk of reducing precision which is why compiler is warning you about. – Pshemo Dec 30 '21 at 10:14
  • 1
    By default Java evaluates `0.002` constant literal to `double`. You may want to have it like `float b = 1 / 0.002F;` – Ervin Szilagyi Dec 30 '21 at 10:15

2 Answers2

1

Use float literals:

float a = 1f / 0.1f;
Ingo
  • 36,037
  • 5
  • 53
  • 100
0

0.1 and 0.002 are double literals. Java’s double type has more precision than its float type. So, when you convert from double to float, the number may be changed by rounding it to the nearest value representable in float. Using decimal as an analogy, assigning the four-digit .1234 to a two-digit type would produce a different number, .12.

When you do this conversion implicitly, by assignment to a float variable, the compiler tells you there could be a loss of information. By using a cast, you tell the compiler the conversion to a less precise format is intentional. Or by using float literals such as 0.1f and 0.002f, you work with float values throughout and avoid conversion.

Generally, pick one type, float or double and use it throughout your calculations, for both literals and variables.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312