Question

I am trying to get a discount of an amount given

lets say: amount = "1.2" and discountPercentage = "17.3"

Code:

orig = Double.parseDouble("amount");
discount = orig*(discountPercentage/100);
discount = Math.round(discount);

discountedprice =  orig - discount;

On the code above: when I round the discount using Math.round(0.2076) i am getting Zero(0) result.

What I want to happen is like this:

0.2076 = should get 0.21 when rounded up

Was it helpful?

Solution 5

float round(float f,float prec)
{
    return (float) (Math.floor(f*(1.0f/prec) + 0.5)/(1.0f/prec));
}

use

round(0.2076f,0.01f)

result

0.21

OTHER TIPS

Try this:

...
discount *= 100;
discount = Math.round(discount);
discount /= 100;
...

Error:

orig = Double.parseDouble("amount");

does not use the variable, but is a string with the content a-m-o-u-n-t.

String amount = "1.2";
double orig = Double.parseDouble(amount);
double discount = orig*(discountPercentage/100);
discount = Math.round(discount);

However be warned, that a double value can only be an approximation of a decimal number, as it is a sum of powers of 2; 0.2 being 2-3 ... Hence 100 * 0.01 is not precisely equal to 1.0.

For financial software it is better to use BigDecimal, which however is more circumstantial though. For a taste:

BigBecimal amount = new BigDecimal("1.20"); // Precision of 2 decimals.
BigDecimal discount = amount.multiply(discountPercentage.movePointLeft(2));

your code will throw a NumberFormatException because of

orig = Double.parseDouble("amount");

You are trying to parse a number from the acutal String "amount". If you already have the amount variable initalized, you should use that variable (remove the quotes in the parseDouble method. E.g.

    String amount = "7.0";
    System.out.println(Double.parseDouble(amount));

Also the types of your variables are not clear: discount, discountPercentage, discountedPrice. Based on the code you provided in your question, a lot is not clear and therefore could be part of your problem.

Don't use Float or Double for money calculations. Use BigDecimal instead as e.g. stated here or here.

Some code:

final BigDecimal orig = new BigDecimal(1.2);
final BigDecimal discountPercentage = new BigDecimal(0.173);
final BigDecimal discount = orig.multiply(discountPercentage);
System.out.println("discount = " + discount.setScale(2, BigDecimal.ROUND_HALF_UP));

Prints:

discount = 0.21

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top