George B George B - 3 months ago 14
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(Formatter.java:1489)
at java.util.Formatter.transformFromFloat(Formatter.java:2038)
at java.util.Formatter.transform(Formatter.java:1465)
at java.util.Formatter.doFormat(Formatter.java:1081)
at java.util.Formatter.format(Formatter.java:1042)
at java.util.Formatter.format(Formatter.java:1011)
at java.lang.String.format(String.java:1554)
at com.georgeberdovskiy.fluidtherapy.MainActivity$1.onClick(MainActivity.java:82)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5444)
at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:746)


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.

Answer

Use this code

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

Please check the link Show only two digit after decimal

Comments