Java – Rounds to 2 decimal places and via TextView

Rounds to 2 decimal places and via TextView… here is a solution to the problem.

Rounds to 2 decimal places and via TextView

Wanted to make a generic division app just to test something because I’m new to everything. I get the final number, I just don’t know how or where to apply NumberFormat or DecimalFormat or how to use Math.Round correctly, so I only get 2 decimal places. I would want to spit any number back into the TextView.

final Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

thing1 = (EditText) findViewById(R.id.thing1);
            if (TextUtils.isEmpty(thing1.getText().toString())) {
                n1 = 0; }
            else {
                n1 = Integer.parseInt(thing1.getText().toString());
            }

thing2 = (EditText) findViewById(R.id.thing2);
            if (TextUtils.isEmpty(thing2.getText().toString())) {
                n2 = 0; }
            else {
                n2 = Integer.parseInt(thing2.getText().toString());
            }

if (n2 !=0){

total = (n1 / n2); }

final double total =  ((double)n1/(double)n2);

final TextView result= (TextView) findViewById(R.id.result);

result.setText(Double.toString(total));

}

});

}

Solution

Try using the String.format() method, which creates a string and rounds that number (up or down) to two decimal places.

String foo = String.format("%.2f", total);
result.setText(foo);

Related Problems and Solutions