3

I want to show only two digits after decimal, i have tried but still i am getting many digits after decimal :

itemamount = Double.parseDouble(text_cost_code.getText().toString());
txt_total.setText(new DecimalFormat("##.##").format(itemamount));

edit_qty_code.addTextChangedListener(new TextWatcher() {

public void onTextChanged(CharSequence s, int start, int before,
        int count) {
// TODO Auto-generated method stub
if (!edit_qty_code.getText().toString().equals("")
|| !edit_qty_code.getText().toString().equals("")) {
itemquantity = Double.parseDouble(edit_qty_code.getText().toString());
itemamount = Double.parseDouble(text_cost_code.getText().toString());
txt_total.setText(new DecimalFormat("##.##").format (itemquantity * itemamount));
} else { txt_total.setText("0.00");}}
Babu
  • 957
  • 1
  • 9
  • 21

4 Answers4

3

I'm not exactly sure where in your code you are wanting to do this, but

String.format("%.2f", value);

should work.

mglowe
  • 134
  • 5
2

Rakesh use this link:

Show only two digit after decimal

  i=348842.
  double i2=i/60000;
  DecimalFormat dtime = new DecimalFormat("#.##"); 
  i2= Double.valueOf(dtime.format(time));
  v.setText(String.valueOf(i2));
Community
  • 1
  • 1
ASMUIRTI
  • 1,332
  • 10
  • 20
0

Try this, it may help you.

float localresult =Float.parseFloat(itemquantity*itemamount);
BigDecimal bd = new BigDecimal(Double.toString(localresult));
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
bd.doubleValue();

then set it to textview , textview.setText(""+bd.doubleValue();)

Abhi
  • 8,935
  • 7
  • 37
  • 60
0

Well if the value of decimal number is dynamic and if not, then here is the solution. (This solution is for both unknown dynamic value or Known value)

 try {
        Double rounded= new BigDecimal(Double.parseDouble(getdecimalvalue())).setScale(2, RoundingMode.HALF_UP).doubleValue();
        textviewid.setText (String.valueOf(rounded) );

    }
    catch (Exception e){
        textviewid.setText (getdecimalvalue());
    }

For upto 2 decimal i give setScale first parameter as 2. Assuming getdecimalvalue() returns a string.

For dynamic suppose if the value is "12.5" then this will throw exception and in catch you directly show the value because value is only upto 1 decimal place after point.

Malick Usman
  • 231
  • 3
  • 6