23

I need to create a String using the Formater to display some double float values. I'm not clear on how to code it. Here is what I have:

Double dWeightInKg = 100;
Double dWeightInLbs = 220:
String headerText = String.format("%.0f kg / %.0f lbs",Double.toString(dWeightInKg) , Double.toString(dWeightInLbs));

I'm looking for the following output:

100 kg / 220 lbs

I get a runtimeexception - badArgumentType(formater) on my String.format line.

3 Answers 3

40

%.0f is the format string for a float, with 0 decimal places.

The values you're passing to String.format are String, String when it needs to be Double, Double.

You do not need to convert the doubles to strings.

String headerText = String.format("%.0f kg / %.0f lbs", dWeightInKg, dWeightInLbs);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. I should have known better!
Also, you will see the hint that you should explicitly determine the locale for String.format(). Avoiding this hint may lead to bugs in your application. More info here: developer.android.com/reference/java/util/…
10

This should work,

DecimalFormat df = new DecimalFormat("#.##");
private String convertToFormat(double value){

    return df.format(value);
}

1 Comment

Thanks for the reply. It was actually something simple.
2

You don't need the Double.ToString() since your formatter is already expecting a number. Try this:

String headerText = String.format("%.0f kg / %.0f lbs", dWeightInKg , dWeightInLbs);

1 Comment

Thanks for the reply. I should have slept on it before asking!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.