This week's book giveaways are in the Refactoring and Agile forums.We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# float representation

Fendel Coulptz
Greenhorn
Posts: 24
hullo,

float f = 30.0;

a compilation error results;

float f = 30;

there's no error, when i print this out it is 30.0;

why is this so? i thought float is a floating-point number? does floating-point number come with decimal places?

and... this is ok,

float f = 30.0f;

what is the f behind it and why can it be used this time round?

and putting a 'd' behind makes it related to double also?

thanks...
confused greenhorn

---
maybe this is too basic, i can't seem to find info abt these online
[ October 25, 2004: Message edited by: Fendel Coulptz ]

Barry Gaunt
Ranch Hand
Posts: 7729
That's because a floating point literal, for example 42.0, is implicitly a Java double. So you would have to write float x = (float)42.0;

The letters f and d are used to denote the primitive types float and double respectively. So 42.0f is a literal of primitive type float, and 42.0d is a literal of primitive type double.
[ October 25, 2004: Message edited by: Barry Gaunt ]

Fendel Coulptz
Greenhorn
Posts: 24
thanks for the quick reply, barry, that cleared my doubts

Fendel Coulptz
Greenhorn
Posts: 24
float f;
long l = 100L;
f = l;

why is float able to be initialized by a long when a float is 32-bit, and a long is 64-bit, and they are of different types?

Layne Lund
Ranch Hand
Posts: 3061
The format for storing floats and longs are significantly different. Because of this the range floats have a larger range than longs, even though floats use less bits. However, you can lose some precision using a float for larger numbers. For the specific maximum and minimum values for these primitive types, you can check out Long and Float in the Java API docs. The Java Language Spedcification also describes these details in all the gory detail.

Layne
[ October 26, 2004: Message edited by: Layne Lund ]

Fendel Coulptz
Greenhorn
Posts: 24
noted, thanks for the prompt reply

Dirk Schreckmann
Sheriff
Posts: 7023
Fendel, when you've time, I'd recommend reading the following lesson on understanding floats.

What Every Computer Scientist Should Know About Floating-Point Arithmetic