0

So I wanted to round my double values into numbers that contain only 2 decimals but cant figure out how to do it. How can I change my code in order to get 2 values that are rounded for 2 decimals? Any help with this would be appreciated.

btnAdd.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        num1 = Double.parseDouble(numBase.getText().toString());
        num2 = Double.parseDouble(numNikotin.getText().toString());
        sum = num1 / 20 * num2;
        String resultN = Double.toString(sum);
        String.format("%.2f", resultN);
        addResult.setText(resultN);
        sum = num1 - sum;
        String resultB = Double.toString(sum);
        String.format("%.2f", resultB);
        addResult2.setText(resultB);
    }
});
tegabyte
  • 69
  • 9
  • 1
    Second sentence of the [documentation for String](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html): *Strings are constant; their values cannot be changed after they are created.* – OH GOD SPIDERS Oct 16 '17 at 10:27
  • 2
    Possible duplicate of [Immutability of Strings in Java](https://stackoverflow.com/questions/1552301/immutability-of-strings-in-java) – Alessandro Da Rugna Oct 16 '17 at 10:59

3 Answers3

4

String.format(...); returns a new String. You have to assign it to a variable:

resultN= String.format("%.2f", sum );

Also the parameter must be numeric.

See the javadoc for more details

Jens
  • 67,715
  • 15
  • 98
  • 113
0

Please check the below post: round up to 2 decimal places in java?

double roundOff = Math.round(a * 100.0) / 100.0;

or

String roundOffTo2DecPlaces(float val)
{
    return String.format("%.2f", val);
}
Amit
  • 1,540
  • 1
  • 15
  • 28
0

use this

String resultN = String.format("%.2f", sum);

why cast to string ????????

String resultN = Double.toString(sum);
String.format("%.2f", resultN);
saman.firouzi
  • 466
  • 5
  • 13