Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

float representation

 
Fendel Coulptz
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the quick reply, barry, that cleared my doubts
 
Fendel Coulptz
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
noted, thanks for the prompt reply
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic