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.