Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Somebody understand this

David Cuesta
Greenhorn
Posts: 25
The code:
public class prDouble{
public static void main(String []arg){
double dYLDAux = Double.parseDouble("+0.0466");
double dHSTAux = Double.parseDouble("+4.9842");
double dAux;
dAux = dYLDAux/dHSTAux;
System.out.println(dAux); //0.009349544560812165
dAux=(double)Math.round(dAux*1000)/1000;
System.out.println(dAux); //0.0090
}
}
do Somebody know why the last zero appears?
I try with others decimal places and this problem don't occurs.
Thanks for all,

Junilu Lacar
Bartender
Posts: 7758
61
Hmmm... odd little quirk there, isn't it? I can appreciate your problem but can offer no solution or explanation although you might try using the Double.doubleToLongBits() and Double.doubleToRawLongBits() and see if you can find variances in what the different powers of ten give you.
[ March 05, 2002: Message edited by: Junilu Lacar ]

Rodney Woodruff
Ranch Hand
Posts: 80
I don't really have an answer for you but I think that it has something to do with the fact that Math.round(a) = (long)Math.floor(a + 0.5d)

Rob Ross
Bartender
Posts: 2205
This has nothing to do with Math.round(). This prints out even if you write
System.out.println(0.0090);
Actually, it's just a formatting issue. println() is implementing a specific formating algorithm, and according to the rules of that particular algorithm, that's how that particular floating point number is being displayed. (Actually println() is using a package-private class FloatingDecimal to do the formatting)
Keep in mind there is a difference between a number's value and the way that number is formatted for display.
For example, say I just have a regular old floating point value like .0090
There's no particular reason why I can't just as well choose to represent that value as:
0.009000
9E-3
9.0E-3
.9E-2
.90E-2
0.09E-1
Etc.
There are infact, infinate ways to represent this quantity. The println()method, when asked to display a floating point double value must pick ONE of these infinate ways, and the method the author of the formatting routine chose results in ".0090".
If you don't like this, you are free to create your own format, using NumberFormat, or more specifically, DecimalFormat. Then you can *always* choose to fomat a value like .0090 for display as ".009" if you like.
Rob
[ March 05, 2002: Message edited by: Rob Ross ]

Junilu Lacar
Bartender
Posts: 7758
61
Actually println() is using a package-private class FloatingDecimal to do the formatting
Rob is correct and has obviously been gophering around the source code. The FloatingDecimal class actually uses Double.doubleToLongBits() to figure out how to display the value, so I was on the right track there, too (just don't ask me to explain that algorithm--we'll leave that up to Rob )
Junilu