This week's book giveaway is in the OCAJP 8 forum.We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!See this thread for details.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!

# 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?