Reputation: 631
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
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:
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
Reputation: 59178
Try this:
public static String roundToOneDigit(float paramFloat) {
return String.format("%.1f%n", paramFloat);
}
Upvotes: 5