1

For the shipping fees and sub total, I have declared it as double. However they just display an amount of 25.0 or 128.0 with just one decimal. I wish to display 25.00 or 128.00 instead. How should I modify my code?

@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);
}
fllo
  • 11,595
  • 5
  • 39
  • 95
Cheong Charlene
  • 315
  • 1
  • 2
  • 9
  • You shouldn't use [floating point for money](http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) anyway. Probably [BigDecimal](http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html) would be better. – Fred Larson Jan 29 '16 at 15:16

2 Answers2

3

If you just want to round it to a '00' value, you can format it as such

String value = String.format("%.2f",price);
Shamas S
  • 7,237
  • 8
  • 44
  • 58
1

Use -

double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.00");
System.out.print(df.format(d));
NehaK
  • 2,128
  • 1
  • 11
  • 29