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

2022-09-01 01:53:58

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


答案 1

Because otherwise it defaults to , which is a more commonly used floating point type than .doublefloat

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


答案 2

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 , because 0.67 has a different value when rounded to float than it does when rounded to double. On the other hand: no

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