EPStudios
EPStudios

Reputation:

Rounding to one decimal place

I im currently working on a temprature converter app. Everything works but I can get over 5 decimals and I have tried to look it up and search on Google but can't find out how do it. Here is where I display the text in the main.java:

text = (EditText) findViewById(R.id.editText1);
result = (TextView) findViewById(R.id.tvResult);
float inputValue = Float.parseFloat(text.getText().toString());
      DecimalFormat df = new DecimalFormat("#.00");
      String s = (String.valueOf(ConvertFahrCels.convertCelsiusToFahrenheit(inputValue)));
      String d = (String.valueOf(ConvertFahrCels.convertFahrenheitToCelsius(inputValue)));

      if (celsiusButton.isChecked()) {
        result.setText(d);
        celsiusButton.setChecked(false);
        fahrenheitButton.setChecked(true);

      } else {
        result.setText(s);
        fahrenheitButton.setChecked(false);
        celsiusButton.setChecked(true);
      }

And here is where I calculate it:

    // converts to celsius
  public static float convertFahrenheitToCelsius(float fahrenheit) {
    return ((fahrenheit - 32) * 5 / 9);

  }

  // converts to fahrenheit
  public static float convertCelsiusToFahrenheit(float celsius) {
    return ((celsius * 9) / 5) + 32;
  }

Upvotes: 1

Views: 1146

Answers (1)

rolfl
rolfl

Reputation: 17707

Your code here implies it is creating a decimal format to do the work, but, you don't actually use it!

  DecimalFormat df = new DecimalFormat("#.00");
  String s = (String.valueOf(ConvertFahrCels.convertCelsiusToFahrenheit(inputValue)));
  String d = (String.valueOf(ConvertFahrCels.convertFahrenheitToCelsius(inputValue)));

The code should be:

  DecimalFormat df = new DecimalFormat("#.00");
  String s = df.format(ConvertFahrCels.convertCelsiusToFahrenheit(inputValue));
  String d = df.format(ConvertFahrCels.convertFahrenheitToCelsius(inputValue));

It is more common in Java now to use String formatting instead of decimal format. Consider:

  String s = String.format("%.1f", ConvertFahrCels.convertCelsiusToFahrenheit(inputValue));

Finally, your question indicates you want 1 decimal place, but, the Decimal format you use adds two.

Upvotes: 3

Related Questions