George B George B - 2 months ago 10x
Java Question

How do I format a double into a string (with only two decimal places)?

I am creating an app for Android using Android Studio. I have a block of code that collects some strings, converts them into doubles, puts them into equations, and then puts the answers into TextViews with only two decimal places.

double weightDouble = Double.parseDouble(weightTextField.getText().toString());
double dehydrationDouble = Double.parseDouble(dehydrationTextField.getText().toString());
double lossesDouble = Double.parseDouble(lossesTextField.getText().toString());
double factorDouble = Double.parseDouble(factorTextField.getText().toString());

double fluidStepOne = (((Math.sqrt(Math.sqrt((weightDouble * weightDouble * weightDouble))))) * 70) * factorDouble;
double fluidStepTwo = fluidStepOne + (weightDouble * dehydrationDouble * 10);
double fluid24Hours = fluidStepTwo + lossesDouble;
double fluidHourInt = fluid24Hours / 24;

fluidResultLabel.setText(String.format(Locale.US, "%.2f", Double.toString(fluid24Hours)));
fluidPerHourResultLabel.setText(String.format(Locale.US, "%.2f", Double.toString(fluidHourInt)));

However, when this block of code is run, the app crashes, and Android Studio says this-

java.util.IllegalFormatConversionException: %f can't format java.lang.String arguments
at java.util.Formatter.badArgumentType(
at java.util.Formatter.transformFromFloat(
at java.util.Formatter.transform(
at java.util.Formatter.doFormat(
at java.util.Formatter.format(
at java.util.Formatter.format(
at java.lang.String.format(
at com.georgeberdovskiy.fluidtherapy.MainActivity$1.onClick(
at android.view.View.performClick(
at android.view.View$
at android.os.Handler.handleCallback(
at android.os.Handler.dispatchMessage( at android.os.Looper.loop( at
at java.lang.reflect.Method.invoke(Native Method) at$

My questions are-

  • How do I fix this problem? (how do I propery format a double into a two-decimal string)

  • Is there anything else I can change to make my code shorter and less prone to bugs?

Thanks!- George

PS- This question is not a duplicate because the answers to questions the same as mine didn't work, and my circumstances are different.


Use this code

fluidPerHourResultLabel.setText(new DecimalFormat("##.##").format(fluidHourInt));

Please check the link Show only two digit after decimal