user
user

Reputation: 631

how to round a float number to one digit in android?

I want to write a method to round the BMI of the user (float number)to one digit, is the logic correct and how to write it in android Java?

private static final DecimalFormat oneDigit = new DecimalFormat("#,##0.0");
      public static float roundToOneDigit(float paramFloat)
  {  
         float   f = Float.valueOf(oneDigit.format(paramFloat)).floatValue();

          f=f;
         return f;

  }

Upvotes: 0

Views: 5960

Answers (2)

Philipp Reichart
Philipp Reichart

Reputation: 20961

Assuming this is for displaying the value to the user:

private static final DecimalFormat oneDecimal = new DecimalFormat("#,##0.0");

public static String formatBmi(double bmi) {
  return oneDecimal.format(bmi);
}

Some changes:

  • Use a double unless you profiled it as a bottleneck, much less downcasts to float
  • You're most likely looking for the term "decimal", not "digit"
  • More descriptive method name

If this gets called concurrently from multiple threads, the static DecimalFormat will break because it is not thread-safe. In that case you might want to test if creating a new one on every method call is fast enough.

Check out Caner's answers, much shorter and inherently thread-safe.

Upvotes: 2

Caner
Caner

Reputation: 59178

Try this:

public static String roundToOneDigit(float paramFloat) {
    return String.format("%.1f%n", paramFloat);
}

Upvotes: 5

Related Questions