This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Possible loss of precision?

 
Scott Callori
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<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.
 
Scott Callori
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the info.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic