1

I have below values, used as testdata to perform subtraction.

order total = $17.99

item Sub Total = $17.99

discount = 20

String orderTotal = "17.99"
String itemSubTotal = "17.99"
String discountPercent = "20"

double discountPercent = Double.parseDouble(discount);

// calculate the discount if given in percentage
double discountAmount = (Double.parseDouble(itemSubTotal) * discountPercent) / 100;
    
// round of the amount
double discountAmount = round(discountAmount, 2);

Double finalOrderTotal = (Double.parseDouble(orderTotal)) - discountAmount;

System.out.println("---------------------"+finalOrderTotal);

And this is method for rounding off the values :

public static double round(double value, int numberOfDigitsAfterDecimalPoint) 
{
    BigDecimal bigDecimal = new BigDecimal(value);
    bigDecimal = bigDecimal.setScale(numberOfDigitsAfterDecimalPoint,
            BigDecimal.ROUND_HALF_UP);
    return bigDecimal.doubleValue();
}

So manual calculation expected result would be 17.99 - 3.60 = 14.39 but what I'm getting is 14.389999999999999

I've tried BigDecimal as suggested in same type of question. but for that again i have to do round of the finalOrderTotal. isn't it ?

Can someone help me to get the simple code (using BigDecimal ) as i'm doing calculation so i can get the correct result.

Community
  • 1
  • 1
NarendraR
  • 7,577
  • 10
  • 44
  • 82
  • This doesn't even compile. There is `discountAmount` declared twice. Where does `round` method come from? What is `subTotal1`? – TheJavaGuy-Ivan Milosavljević Jul 27 '18 at 14:59
  • @TheJavaGuy-IvanMilosavljević, Hey I have updated the question now. please have a look – NarendraR Jul 28 '18 at 06:07
  • You use BigDecimal to do the rounding, but the rest is floating point, and that has a limited precision. So you are bound to get differences (even Double.parse() will just give you the best estimate). Use BigDecimal everywhere and you get exact results. – Rudy Velthuis Jul 28 '18 at 16:01

1 Answers1

0
    String orderTotal = cart.getOrdertotal();
    String itemSubTotal = cart.getItemPrice();

    String orderTotal1 = orderTotal.replace(currency, "");
    String itemSubTotal1 = itemSubTotal.replace(currency, "");

    double discountPercent = Double.parseDouble(discount);

    // calculate the discount if given in percentage
    double discountAmount =
            (Double.parseDouble(itemSubTotal1) * discountPercent) / 100.0;

    // round of the amount
    double discountAmount = round(discountAmount, 2);

    Double finalOrderTotal = (Double.parseDouble(subTotal1)) - discountAmount;
    System.out.println("---------------------"+finalOrderTotal);
Bartors
  • 180
  • 1
  • 16
Marco Rocchi
  • 138
  • 1
  • 10