Why do you need to specify a suffix f
in a float literal?
Why is it used? The "F" indicates that the literal numeric value it is appended to is a float value. This is necessary information for the compiler and if not present can lead to errors or the compiler otherwise interpreting the number incorrectly.
We must add the suffix f or F at the end of a float value. This is because the compiler interprets decimal values without the suffix as double . Consider this code.
float variables can be represented with a lowercase 'f' OR uppercase 'F' at the end, which asks the program specifically for a single-precision float literal which deals with a 32 bit floating point. Even without the 'f' or 'F' at the end the program, it assumes a float is declared and initialized.
In Python, there are various methods for formatting data types. The %f formatter is specifically used for formatting float values (numbers with decimals). We can use the %f formatter to specify the number of decimal numbers to be returned when a floating point number is rounded up.
Because otherwise it defaults to double
, which is a more commonly used floating point type than float
.
From the Java Language Specification, section 3.10.2:
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d (§4.2.3).
(Personally I'd rather there were no default, to make it clear in all cases, but that's a different matter.)
Because unsuffixed floating-point literals are doubles, and rounding means that even small literals can take on different values when rounded to float and double. This can be observed in the following example:
float f = (float) 0.67; if(f == 0.67) System.out.print("yes"); else System.out.print("no");
This will output no
, because 0.67 has a different value when rounded to float than it does when rounded to double. On the other hand:
float f = (float) 0.67; if(f == 0.67f) System.out.print("yes"); else System.out.print("no");
… outputs yes
.
EDIT
Second example:
if(0.67 == 0.67f) System.out.print("Equal"); else System.out.print("Not Equal");
… outputs Not Equal
.
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