如何显示仅包含两位小数的数字

3

我想只显示小数点后两位,但是尝试了很多方法仍然会得到很多小数位:

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");}}
4个回答

3

我不确定您想在代码的哪个部分进行这项操作,但是

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

应该工作。


2

Rakesh使用此链接:

显示小数点后两位

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

0

试试这个,它可能会对你有帮助。

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

然后将其设置为TextView,textView.setText(""+bd.doubleValue());


0

如果十进制数的值是动态的,或者如果不是,那么这里有一个解决方案。(此解决方案适用于未知动态值或已知值)

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

如果要保留两位小数,可以将setScale方法的第一个参数设置为2。假设getdecimalvalue()返回一个字符串。

对于动态值,例如"12.5",这会抛出异常,在catch块中直接显示该值,因为该值只有小数点后一位。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接