How to show only two digits after the decimal

I only want to show two digits after the decimal , I tried, but still I get a lot of digits after the 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");}}

      

+3


source to share


4 answers


Rakesh uses this link:

Show only two digits after the decimal value



  i=348842.
  double i2=i/60000;
  DecimalFormat dtime = new DecimalFormat("#.##"); 
  i2= Double.valueOf(dtime.format(time));
  v.setText(String.valueOf(i2));

      

+2


source


I'm not really sure where in the code you want to do, but

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

      



must work.

+3


source


Try this, it might 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 ();)

0


source


Ok if the decimal value is dynamic, if not then here is the solution. (This is the solution for both unknown dynamic value and 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 decimal up to 2, I set the first parameter to setScale as 2. Assuming getdecimalvalue () returns a string.

To dynamically assume that if the value is "12.5" then this will throw an exception and in the catch you will directly map the value, because the value is only up to 1 decimal place after the dot.

0


source







All Articles