Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

Possible loss of precision?

Scott Callori
Greenhorn
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): ");
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: 9063
12
<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
Thank you for the info.

Peter Chase
Ranch Hand
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.