aspose file tools*
The moose likes Beginning Java and the fly likes float error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "float error" Watch "float error" New topic
Author

float error

Adam Vinueza
Ranch Hand

Joined: Apr 16, 2001
Posts: 76
I'm new to Java, and have been working my way through _Java in 21 days_, when I wrote this simple program to help myself understand casting better:
public class CastEx
{
public static void main(String[] arguments)
{
float k = 4.57;
k = (int)k;
System.out.println(k);
}
}
I got the following error message:
possible loss of precision
found: double
required: float,
followed by a little arrow pointing at the numeral 4.
This message seems to me to be telling me that I have somehow used a double type instead of a float, when float is specified in the program. What is happening here? I feel like I'm making some kind of basic, easy-to-fix error, but I don't see what I'm doing wrong.
Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241
It's OK, Adam, it's how we all learn.
Just as Java takes integral literals ( -8, 0, 14, +55, 1234567891011 ) to be ints, it takes decimal literals ( -2e10, -0.0, 5., 4.57 ) to be doubles. All you have to do to convince Java that 4.57 is a float and not a double is suffix it with f or F:

In the same way, if you want Java to consider an integral value to be a long, you have to suffix it with an l or an L. (The uppercase version is preferred, because the lowercase version can so easily be confused with the number 1.)
Hope this helps, Adam.
Art
Magesh Lakshmi
Greenhorn

Joined: Nov 09, 2000
Posts: 7
Hi,
The reason is that when you try to store a float to an int, the precision would be lost.
So that if you try to store 5.7 ( which is a float ) to a int variable then it will store only 5.
Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241
I also found this link for you, Adam, at the Java Language Specification:
http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#230798
Art
Adam Vinueza
Ranch Hand

Joined: Apr 16, 2001
Posts: 76
Thanks to Art and Magesh for your helpful comments. Of course the problem would turn out to have such a simple solution--would that all problems could be solved like that!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: float error
 
Similar Threads
Wrapper classes doubt?
question regarding method invocation's parameter widening/narrowing
Constructor Arguments for Wrapper Class Float
method arguments ?
Method Overloading