I wrote this code:
float b = 3.6;
and I get this:
Error:Unresolved compilation problem: Type mismatch: cannot convert from double to float
Why? Whats the definition of float
?
A float data type in Java stores a decimal value with 6-7 total digits of precision. So, for example, 12.12345 can be saved as a float, but 12.123456789 can't be saved as a float. When representing a float data type in Java, we should append the letter f to the end of the data type; otherwise it will save as double.
Float is a single-precision value that has a width of 32 bits in storage. On some processors, this single precision is faster and takes less size when compared to the double-precision. This is arguable as on some modern processors, double-precision is faster than the single-precision.
float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification.
Float is a datatype which is used to represent the floating point numbers. It is a 32-bit IEEE 754 single precision floating point number ( 1-bit for the sign, 8-bit for exponent, 23*-bit for the value. It has 6 decimal digits of precision.
In Java, when you type a decimal number as 3.6
, its interpreted as a double
. double
is a 64-bit precision IEEE 754 floating point, while float
is a 32-bit precision IEEE 754 floating point. As a float
is less precise than a double
, the conversion cannot be performed implicitly.
If you want to create a float, you should end your number with f
(i.e.: 3.6f
).
For more explanation, see the primitive data types definition of the Java tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With