programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# float representation

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 ]

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?

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

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

 Destiny's powerful hand has made the bed of my future. And this tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS