how is it possible to precise a float number in java
Hello ,
It is my second post and i couldnt find an answer to it. The problem ii want to display a float number with only the last three decimal after the comma. For example, float x = 23.445566 and i need to display only 23.445
How can i do that ? here is the code:
int val1 = 1432;
int val2 = 13;
float result = 0.000F
(float) (valu1/valu2)
the result = 110.153846...
And what i want to display is 110.153
Please help.
Thanks
[501 byte] By [
seekera] at [2007-10-2 12:04:28]

If you really want to truncate the value, look at Math.floor(). 1e-3 * Math.floor(1e3 * 110.153846) ~ 110.153
If you want to format the output to a fixed number of figures, use java.text.DecimalFormat. That will round the number using half even rounding, so 110.153846 will be outputted as 110.154.
Pete
I stand corrected. I didn't realize that did rounding at all. I don't like that. That shouldn't do any ronding, in MY opinion. Ohwell.However, rounding up on a 6 isn't a sign of half even rounding.
I must be misunderstanding. Are you saying that a .6 is "half" and therefor will always round to the nearest even? When I round .6 using printf and %.0f I get a 1. Heck, on my computer when I do the same to a .5 I get a 1. 1 isn't even.
.6 rounding up indicates only that the rule isn't to always round down.
the documentation says it uses "round half up" ...
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#dndec
"If the precision is less than the number of digits which would appear after the decimal point in the string returned by Float.toString(float) or Double.toString(double) respectively, then the value will be rounded using the round half up algorithm."
You're right - java.text.Decimal format uses round half even, java.util.Formatter uses round half up.
Float f = 0.5F;
System.out.printf("%.0f\n", f);
System.out.println(new java.text.DecimalFormat("0").format(f));
1
0
In the ASNI C implementations I've worked with, printf also uses half-even.
Bizarre.
Pete