File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Somebody can explain me? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Somebody can explain me?" Watch "Somebody can explain me?" New topic
Author

Somebody can explain me?

David Cuesta
Greenhorn

Joined: Nov 07, 2001
Posts: 25
double dAux;
...
dAux=Math.round((dAux*1000));
dAux/=1000;
// diferent result
dAux=(Math.round((dAux*1000)))/1000;
...
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by David Cuesta:
double dAux;
...
dAux=Math.round((dAux*1000));
dAux/=1000;
// diferent result
dAux=(Math.round((dAux*1000)))/1000;
...

I believe what you're seeing is caused by the fact that Math.round returns an int, rather than a double. This is causing integer division (using truncation) to be done instead of floating point division. I used the following code:

and I got the results:
12.6
12.0
However, if I modify the code slightly to look like this:

I then get this as my output:
12.6
12.6
In the second case, Because Math.round(double) returns an int, both operands are inetegers and integer division is being performed. In the first case, since dAux is a double, floating point division takes place automatically (because one of the two operands is a double). You need to specifiy explicitly (through the use of a cast) what type of division you want to occur. By casting the result as a double in the second case, I'm telling the JVM that I want it to perform this division but, even though both operands are integers, I want to use floating point division and avoid the truncation you were originally seeing.
I hope this all makes sense.
Corey
[This message has been edited by Corey McGlone (edited December 27, 2001).]


SCJP Tipline, etc.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Somebody can explain me?
 
Similar Threads
SimpleDateFormat (calculation)
rounding float value
Rounding of float value
Getting rid of unwanted decimal numbers
Number of days between the 2 given dates.