3

want to make generic dividing app just to test some stuff out because I'm pretty new at everything still. I get the final number, I just don't know how or where to apply NumberFormat or DecimalFormat or how to properly Math.Round so I only get 2 decimal places as a result. I'll want to spit whatever number divided out back into a text view.

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));

        }

    });


}
pjhollow
  • 85
  • 1
  • 6

4 Answers4

3

Try using the String.format() method, it will create a string with that number rounded (up or down as appropriate) to two decimal places.

String foo = String.format("%.2f", total);
result.setText(foo);
zxgear
  • 1,168
  • 14
  • 30
1

you can use String.format()

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

OR

use Math.round()

Math.round(total*100.0)/100.0

like this:

result.setText(Double.toString(Math.round(total*100.0)/100.0));
Dyrandz Famador
  • 4,499
  • 5
  • 25
  • 40
1

Try using this code:

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setGroupingSeparator(',');
dfs.setDecimalSeparator('.');
df.setDecimalFormatSymbols(dfs);
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
result.setText(df.format(n1 / n2));

Hoping it's work. Thanks

Trang
  • 11
  • 1
0

You should try this

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