Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the letter f used at the end of a float no.?

Tags:

java

I just wanted some information about this.

float n = 2.99944323200023f

What does the f at the end of the literal do? What is it called? Why is it used?

like image 544
crvineeth99 Avatar asked Dec 04 '12 13:12

crvineeth99


People also ask

Why do you put F after float?

In c a value of 1 is an integer and 1.0 is a double, you use f after a decimal number to indicate that the compiler should treat it as a single precision floating point number.

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 mean at the end of a number?

By default, a numeric literal that contains a decimal point is of type double . If you want a numeric literal of type float instead, then you put an f after it.

What does F do in Java?

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. The default value of a float in Java is 0.0f. Float data type is used when you want to save memory and when calculations don't require more than 6 or 7 digits of precision.


1 Answers

The f indicates it's a floating point literal, not a double literal (which it would implicitly be otherwise.) It hasn't got a particular technical name that I know of - I tend to call it the "letter suffix" if I need to refer to it specifically, though that's somewhat arbitrary!

For instance:

float f = 3.14f; //Compiles
float f = 3.14;   //Doesn't compile, because you're trying to put a double literal in a float without a cast.

You could of course do:

float f = (float)3.14;

...which accomplishes near enough the same thing, but the F is a neater, more concise way of showing it.

Why was double chosen as the default rather than float? Well, these days the memory requirements of a double over a float aren't an issue in 99% of cases, and the extra accuracy they provide is beneficial in a lot of cases - so you could argue that's the sensible default.

Note that you can explicitly show a decimal literal as a double by putting a d at the end also:

double d = 3.14d;

...but because it's a double value anyway, this has no effect. Some people might argue for it advocating it's clearer what literal type you mean, but personally I think it just clutters code (unless perhaps you have a lot of float literals hanging around and you want to emphasise that this literal is indeed meant to be a double, and the omission of the f isn't just a bug.)

like image 175
Michael Berry Avatar answered Sep 27 '22 20:09

Michael Berry