Android rounding with decimal format

I want to set Rounding Mode to HALF_UP on my DecimalFormat, but eclipse tells me that setRoundingMode () is not available in the DecimalFormat class. My project properties (and general Eclipse properties) use compiler 1.6. Developer.android.com 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 also tried using the android tools to create an ant based project, tried this code in the project and also got the same compilation error. Therefore, it does not seem to be related to Eclipse. This is similar to the Android API.

Any suggestions?

+4
source share
3 answers

This really doesn't answer why I cannot use the Java.setRoundingMode (RoundingMode) method in DecimalFormat, but this is at least a workaround.

 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 BigDecimal of that value when the scale is set to the number of digits I need to round my values ​​to. Then I pass this rounded value to my original NumberFormat for conversion to String.

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

+8
source

Here is what I suspect, the problem is (if I read the documents correctly) and its doozy:

According to the java.text.DecimalFormat API documentation, you are not actually using Runtime Implimentation Java 1.6 RE, but you are getting the β€œExtended Version” android, which clearly does not contain setRoundingMode, which frankly bites.

"This is an extended version of DecimalFormat, based on the standard version in RI. New or changed functionality is marked as NEW."

The weakness of Java for many years was the default DecimalFormat class HALF_ROUND_UP and was not able to change this until the JVM 1.6. Too bad Android supports this need to kill a living.

So it looks like we're stuck. Kludging BigDecimal scale Settings for formatting the output for all the applications that it needs, instead of just being able to rely only on the formatting call to do the job. Not the end of the world, but very disappointing Google.

Of course, the same dock says that setRondingMode () works, maybe it's all due to an error?

+3
source

All Articles