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

Possible loss of precision?

Scott Callori
Greenhorn

Joined: Dec 03, 2001
Posts: 2
Why is it that this code gives me a possible loss of precision error?
public class ship {
public static void main(String[] args){
float cost=0, weight=0;
System.out.print("Please enter weight of parcel(kg): ");
weight=Keyboard.readFloat();
if(weight<2.5)
cost=weight*3.5;
else if(weight<5)
cost=weight*2.85;
else if(weight>5)
cost=weight*2.45;
System.out.println("The cost to ship will be $"+cost);
}
}
To not get the error I must cast it as a float?
cost=(float)(weight*2.45);
I don't quite understand this when both cost and weight are both floats.
[This message has been edited by Scott Callori (edited December 03, 2001).]
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9046
    
  10
<br /> To not get the error I must cast it as a float?<br /> cost=(float)(weight*2.45);<br /> I don't quite understand this when both cost and weight are both floats.<br /> <br /> In Java, numbers with decimal points default to doubles, so 2.45 is a double. float * double => double. Therefore you need to cast it back to a float to be able to assign it to cost which is a float.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Scott Callori
Greenhorn

Joined: Dec 03, 2001
Posts: 2
Thank you for the info.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
All that casting will make the code look nasty. Instead, when doing arithmetic with floats, not doubles, use float literals. That is, put an "f" on the end of each literal.
For instance, 3.45 is a double literal, 3.45f is a float literal.
You may also improve performance this way. I suspect that, if you use double literals, there really will be a conversion of your float variable value into a double, a calculation in double precision and a conversion back to float.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Possible loss of precision?