简体   繁体   中英

Android Studio - DecimalFormat (java.text) - Not working properly

So, I have this following code to make a simple temperature app converter in Android Studio 4.0.1:

bt_converter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    double tempC = Double.parseDouble(et_tempC.getText().toString());

    DecimalFormat arredondar = new DecimalFormat("#.##");
    double tempF = Double.parseDouble(arredondar.format(tempC * 1.8 + 32));

    tv_tempF.setText(String.valueOf(tempF));
}

The problem is that when I run the app it crashes due to this statement: DecimalFormat arredondar = new DecimalFormat("#.##"); And the same for: DecimalFormat arredondar = new DecimalFormat("0.00");

In fact it crashes with every pattern started by "0" and involving point "."

I've tried to switch it to: DecimalFormat arredondar = new DecimalFormat("#,##");

And it actually works but it is not showing two decimal places as intended, and no matter what tempC value I put in, the output is always some number point zero (xx.0) .

For example: for tempC = 10.11111111 it shows tempF = 50.0 When it should give me 50.19 or 50.2 instead.

I've reinstalled the app and cleaned the project, and even changed my windows 10 region settings (with regards to decimal symbols), but it still remains the same.

But please let me know if you need more details.

So, I came to a solution, and it works as intended. I just changed the three last lines of code:

Before

DecimalFormat arredondar = new DecimalFormat("#.##");

double tempF = Double.parseDouble(arredondar.format(tempC * 1.8 + 32));
tv_tempF.setText(String.valueOf(tempF));

After:

DecimalFormat arredondar = new DecimalFormat("0.00");
double tempF = tempC * 1.8 + 32;

tv_tempF.setText(arredondar.format(tempF));

Apparently there is some king of error/incompatibility. But, I realised that I was converting tempF from String to Double with the second line in the before code, and then convert it back again to String with the third one.

So I simply put the tempF directly in the output with a String format, after having calculated it with no convertion:

            double tempF = tempC * 1.8 + 32;

            tv_tempF.setText(arredondar.format(tempF));

And I've changed the pattern from "#.##" to "0.00" to make sure that I get two decimal places everytime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM