如何为双变量舍入到2位小数?

时间:2016-01-29 15:03:00

标签: java android double

对于运费和小计,我已将其声明为double。然而    它们只显示一个小数点25.0128.0。我希望改为显示25.00128.00。我该如何修改我的代码?

@Override
protected void onResume() {
    super.onResume();

    // Refresh the data
    if(mProductAdapter != null) {
        mProductAdapter.notifyDataSetChanged();
    }

    double totalweight = 0;
    double shippingfee = 0;
    for(product p : mCartList) {
        int quantity = ShoppingCartActivity.getProductQuantity(p);
        totalweight += p.weight * quantity;
        shippingfee = ShoppingCartActivity.getShipping(totalweight);
    }

    double subTotal = 0;
    for(product p : mCartList) {
        int quantity = ShoppingCartActivity.getProductQuantity(p);
        subTotal += p.price * quantity;
    }
    if (subTotal >= 150){
        shippingfee = 0;
        subTotal += shippingfee;
    }
    else{
        for(product p : mCartList) {
            int quantity = ShoppingCartActivity.getProductQuantity(p);
            totalweight += p.weight * quantity;
            shippingfee = ShoppingCartActivity.getShipping(totalweight);
        }
        subTotal += shippingfee;
    }
    TextView productPriceTextView = (TextView) 
    findViewById(R.id.TextViewSubtotal);
    productPriceTextView.setText("Subtotal: RM" + subTotal);
    TextView productWeightTextView = (TextView) 
    findViewById(R.id.TextViewSubweight);
    productWeightTextView.setText("Shipping Weight: " + totalweight +" kg");
    TextView productShippingTextView = (TextView) 
    findViewById(R.id.TextViewShipping);
    productShippingTextView.setText("Shipping Fee: RM" + shippingfee);
}

2 个答案:

答案 0 :(得分:3)

如果您只是想将其四舍五入到' 00'值,您可以将其格式化为

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

答案 1 :(得分:1)

使用 -

double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.00");
System.out.print(df.format(d));