Home > other >  Java: incompatible types, possible lossy conversion from double to float
Java: incompatible types, possible lossy conversion from double to float

Time:12-31

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.

CodePudding user response:

Use float literals:

float a = 1f / 0.1f;

CodePudding user response:

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.

  • Related