It's not a secret anymore!
The moose likes Beginning Java and the fly likes Integer division, Urgent Please Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Integer division, Urgent Please" Watch "Integer division, Urgent Please" New topic
Author

Integer division, Urgent Please

Kishan Kumar
Ranch Hand

Joined: Sep 26, 2000
Posts: 130
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


Regards,<BR>V. Kishan Kumar
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4115
    
    2

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).]


Junilu - [How to Ask Questions] [How to Answer Questions] [MiH]
 
I agree. Here's the link: http://jrebel.com/download
 
subject: Integer division, Urgent Please
 
Similar Threads
access control
casting
File Object, Poddar Exam Q: 41
Abstract class code
scjp chapter 3