Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# DecimalFormat average

Kevin Tysen
Ranch Hand
Posts: 255
I have this in my program, (almost like this, anyway).

int cT = 17;
int ns = 4;
NumberFormat f = new DecimalFormat("0.0");
double ts = (double) cT;
double n = (double) ns;
writer.write(f.format(ts / n));

And when I run the program I think I should get 4.3, because 17/4 is 4.25, but I get 4.2. Why is that? What can I do about it?

Henry Wong
author
Marshal
Posts: 21123
78
According to the JavaDoc, DecimalFormat uses "half even rounding", which is described as...

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.

Henry

Kevin Tysen
Ranch Hand
Posts: 255
Thank you. But what is JavaDoc? I looked at the API for both NumberFormat and DecimalFormat, but I couldn't find the quote you quoted.

I assume one can use ROUND_HALF_UP like this?

myFormat = new NumberFormat("0.0");
myFormat.setRounding(NumberFormat.ROUND_HALF_UP);

Of course, it must be a different class. Well, if you can tell me how to look at JavaDoc, I can study it for myself.

marc weber
Sheriff
Posts: 11343
Yes, JavaDoc is the tool that produces the API documentation. Under DecimalFormat, the API documentation says...
Rounding

DecimalFormat provides rounding modes defined in RoundingMode for formatting. By default, it uses RoundingMode.HALF_EVEN.

When you click on RoundingMode.HALF_EVEN, you are taken to the definition Henry quoted from java.math.RoundingMode.

Using the setRoundingMode method in DecimalFormat will change this as desired...

myFormat.setRoundingMode(RoundingMode.HALF_UP);

Kevin Tysen
Ranch Hand
Posts: 255
I was looking at the API for Java 1.3 and that is why I couldn't find the quote. The API for DecimalFormat in Java 1.3 says nothing about rounding.

I have one computer with Java 1.3 and one with Java 1.5 and my program so far runs on both computers.

Java 1.5 has a note about rounding, but it refers to a field in the class BigDecimal. I think Java 1.3 has BigDecimal, too, so I will look carefully at the API for BigDecimal and see if I can use it to do what I want, or maybe link it somehow to NumberFormat or DecimalFormat.

Henry Wong
author
Marshal
Posts: 21123
78
so I will look carefully at the API for BigDecimal and see if I can use it to do what I want,

Take a look at the setScale() method. With Java 1.3, that's probably the easiest way to get what you want.

Henry