Reputation: 957
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");}}
Upvotes: 3
Views: 7877
Reputation: 281
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.
Upvotes: 0
Reputation: 1332
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));
Upvotes: 2
Reputation: 9005
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();)
Upvotes: 0
Reputation: 135
I'm not exactly sure where in your code you are wanting to do this, but
String.format("%.2f", value);
should work.
Upvotes: 3