如何在小数点后仅显示两位数

时间:2013-02-20 05:37:37

标签: android

我获得了mGTotal的价值,如:179.257856

但现在我只想在小数点后只显示两位数,例如:179.25

    @Override
    protected void onResume() 
    {
        super.onResume();
        if (Constants.mItem_Detail.size() == 0) 
        {
            return;
        }

        Double mGTotal = Double.parseDouble(Constants.mItem_Detail.get(0).get(SingleProductActivity.KEY_TOTAL));
        for (int i = 1; i < Constants.mItem_Detail.size(); i++) 
        {   
        mGTotal = mGTotal + Double.parseDouble(Constants.mItem_Detail.get(i).get(SingleProductActivity.KEY_TOTAL));
        }
        mGrandTotal = String.valueOf(mGTotal);
        mTxtViewGrandTotal.setText(mGrandTotal);
        myTextVeiwGrandTotal.setText(mGrandTotal);
        mTotal = String.valueOf(Constants.mItem_Detail.size());
        mItems.setText(mTotal);

}
}

2 个答案:

答案 0 :(得分:7)

使用Decimalformat

DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format("179.257856"));// which gives result as 179.25

答案 1 :(得分:3)

你非常接近你的回答,我想下面的行对你有用:

 mTxtViewGrandTotal.setText(new DecimalFormat("##.##").format(mGTotal));

并且完整方法应该如下所示:

   @Override
    protected void onResume() 
    {
        super.onResume();
        if (Constants.mItem_Detail.size() == 0) 
        {
            return;
        }

        Double mGTotal = Double.parseDouble(Constants.mItem_Detail.get(0).get(SingleProductActivity.KEY_TOTAL));
        for (int i = 1; i < Constants.mItem_Detail.size(); i++) 
        {   
        mGTotal = mGTotal + Double.parseDouble(Constants.mItem_Detail.get(i).get(SingleProductActivity.KEY_TOTAL));
        }
        mGrandTotal = String.valueOf(mGTotal);
        mTxtViewGrandTotal.setText(mGrandTotal);
        myTextVeiwGrandTotal.setText(mGrandTotal);
        mTxtViewGrandTotal.setText(new DecimalFormat("##.##").format(mGTotal));
        mTotal = String.valueOf(Constants.mItem_Detail.size());
        mItems.setText(mTotal);

}