I just wanted some information about this.
float n = 2.99944323200023f
What does the f
at the end of the literal do? What is i
From the Oracle Java Tutorial, section Primitive Data Types under Floating-Point Literals
A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.
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.)
When you write 1.0, it's ambiguous as to whether you intend the literal to be a float or double. By writing 1.0f, you're telling Java that you intend the literal to be a float, while using 1.0d specifies that it should be a double (which is also default if you do not specify that explicitely).
It's to distinguish between floating point and double precision numbers. The latter has no suffix.
In Java, when you type a decimal number as 3.6
, its interpreted as a double
. double
is a 64-bit precision IEEE 754 floating point, while float
is a 32-bit precision IEEE 754 floating point. As a float
is less precise than a double
, the conversion cannot be performed implicitly.
If you want to create a float, you should end your number with f
(i.e.: 3.6f
).
For more explanation, see the primitive data types definition of the Java tutorial.
It means that it's a single precision floating point literal rather than double precision. Otherwise, you'd have to write float n = (float)2.99944323200023;
to cast the double to single.