Question

I want to set the Rounding Mode to HALF_UP on my DecimalFormat, but eclipse is telling me that setRoundingMode() is not available on the DecimalFormat class. My project properties (and the overall Eclipse properties) are using the 1.6 compiler. The developer.android.com site says that I can use either Java 5 or 6 so I'm not sure what the problem is.

import java.math.RoundingMode;
import java.text.DecimalFormat;

completedValueFormatter = NumberFormat.getNumberInstance(); DecimalFormat completedDecimalFormat = (DecimalFormat)completedValueFormatter; completedDecimalFormat.setRoundingMode(RoundingMode.HALF_UP);

I've also tried using the android tools to generate an ant-based project, tried this code in the project and also got the same compile error. So it doesn't appear to be related to Eclipse. It seems related to the Android API.

Any suggestions?

Was it helpful?

Solution

This doesn't truly answer why I can't use the Java 6 .setRoundingMode(RoundingMode) method in DecimalFormat, but it is at least a work-around.

int numDigitsToShow = this.completedValueFormatter.getMaximumFractionDigits();
BigDecimal bigDecimal = new BigDecimal(valueToBeRounded);
BigDecimal roundedBigDecimal = bigDecimal.setScale(numDigitsToShow, RoundingMode.HALF_UP);

return this.completedValueFormatter.format(roundedBigDecimal.doubleValue());

I create a BigDecimal with the value I need to round, then I get a BigDecimal of that value with the scale set to the number of digits I need to round my values to. Then I pass that rounded value off to my original NumberFormat for conversion to String.

If anyone has a better solution, I'm all ears!

OTHER TIPS

Here is what I suspect the problem is, (assuming I am reading the docs properly) and its a doozy:

According to the java.text.DecimalFormat API documentation, you are not actually getting the Runtime Implimentation of the Java 1.6 RE, but are getting an android "Enhanced Version" that clearly doesn't include the setRoundingMode, which frankly bites.

"This is an enhanced version of DecimalFormat that is based on the standard version in the RI. New or changed functionality is labeled NEW."

A weakness in Java for many many many years has been the DecimalFormat class defaulted to HALF_ROUND_UP and had no way to change that, until JVM 1.6. Pity to see Android is keeping this need to kludge alive.

So looks like we are stuck Kludging BigDecimal scale Settings to format output all over any app that needs it, instead of simply being able to rely on a formatter call alone to get the job done. Not the end of the world, but very disappointing Google.

Of course that same doc says that setRondingMode() works, so perhaps this is a all out BUG??

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top