Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Integer division, Urgent Please  RSS feed

 
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Folks,
When I try to divide numbers like this
floatt f1 = 8/2000;
System.out.println("oytput of 8/2000 = "+f1);
The output is 0.0
But i want it as 0.004. How to write code to get this.
Please suggest.


------------------
Regards,
V. Kishan Kumar
 
Sheriff
Posts: 12009
196
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read up on how conversion works in Java. You get 0.0 because 8 and 2000 are both seen by the compiler as integers. The result of integer division is always an integer. Java also truncates the result. Thus the result of (8/2000) is the integer value 0 which is then automatically converted to a float (0.0f) and assigned to the variable f1. One solution for you would be to make at least one of your operands a float, e.g.


Note that floating point calculations may lose precision so you may or may not get the exact results that you are looking for.
HTH
J. Lacar

[This message has been edited by JUNILU LACAR (edited March 02, 2001).]
 
What's that smell? I think this tiny ad may have stepped in something.
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!