Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why f is placed after float values?

I don't know why f or F is placed after float values in Java or other languages? for instance,

float fVariable = 12.3f; 

any features other than indicating that this is a float value?

like image 602
ipkiss Avatar asked Mar 17 '12 07:03

ipkiss


People also ask

Why do we use F in C# float?

Why is the f is required at the end of this number? Probably, because otherwise it would be treated as double . 0.58 (without the f suffix) is a literal of type double and one cannot assign a double value to a float, just like one cannot assign an int value to a string.

What does F after a number mean in C?

From C. It means float literal constant.

Is %f for float in C?

The f suffix simply tells the compiler which is a float and which is a double .

Is 5f a float in Java?

5 is of type integer where as 5f is of type float. Positions tend to use floats and doubles, since you need precision.


2 Answers

by default 12.3 is double literal, So to tell compiler to treat it as float explicitly -> it uses f or F

like image 153
jmj Avatar answered Sep 21 '22 18:09

jmj


Seeing as there are only so many ways to represent a number in your program, the designers of Java had to cherry pick and assign each form to the most common use case. For those forms selected as default, the suffix that denotes the exact type is optional.

  • For Integer literals (int, long), the default is int. For obvious reasons.
  • For Floating point literals (float, double) the default is double. Because using double potentially allows safer arithmetic on the stored values.

So, when you type 12 in your program, thats an int literal, as opposed to 12L, which is a long. And when you type 12.3, thats a double literal, as opposed to 12.3F, which is a float.

So where is this relevant? Primarily in handling downcasts, or narrowing conversions. Whenever you downcast a long to an int, or a double to a float, the possibility for data loss exists. So, the compiler will force you to indicate that you really want to perform the narrowing conversion, by signaling a compile error for something like this:

float f = 12.3; 

Because 12.3 represents a double, you have to explicitly cast it to a float (basically signing off on the narrowing conversion). Otherwise, you could indicate that the number is really a float, by using the correct suffix;

float f = 12.3f; 

So too summarize, having to specify a suffix for longs and floats is a compromise the language designers chose, in order to balance the need to specify what exactly a number is, with the flexibility of converting numbers from one storage type to another.

like image 42
Perception Avatar answered Sep 24 '22 18:09

Perception