• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

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: 12502
206
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).]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!