• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Possible loss of precision?

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).]
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for the info.
 
Ranch Hand
Posts: 1970
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic