Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Why do you need to specify an 'f' in a float literal? [duplicate]

Why do you need to specify a suffix f in a float literal?

like image 569
stackoverflow Avatar asked Dec 31 '12 14:12

stackoverflow


People also ask

Why do you need the F in float Java?

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.

Why do you need f after float?

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.

Can we declare float without F in Java?

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.

Is %f used for float?

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.


2 Answers

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.)

like image 138
Jon Skeet Avatar answered Sep 22 '22 05:09

Jon Skeet


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.

like image 31
Grijesh Chauhan Avatar answered Sep 18 '22 05:09

Grijesh Chauhan