Rounding Half Up with Decimal Format in Android

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?

Answers


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!


Need Your Help

How to start facebook app?

php ruby-on-rails ruby facebook

Just want to know what is better way to get start developing faccebook app?Any tutorial recommnedation?And which is better to start up -php or rails?

Java BoundingBox programm

java eclipse

I'm beginner with programming in Java. I would make an application to count max Point, min Point, width and height. I write in eclipse.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.