Amanda Merical
Amanda Merical

Reputation: 23

Java decimals using %.2f

I'm new to java and I'm writing a code for a monthly payment calculator, the only problem that I'm having is rounding errors that I'm getting. I need to calculate the monthly payments which I did by:

System.out.printf("Your monthly payment will be:$%.2f", payment);

this part is coming out ok

Now I have to figure out how much they will pay at the end of their payments so I did :

System.out.printf("You will be paying a total amount of $%.2f", payment * months);

This is where my problem lies, in the first print out it's rounding the payment, in the second print out its rounding the payment times the months, I need it to round ONLY the payment and then multiply that by the months but I can't figure out how. Any help would be great.

Upvotes: 2

Views: 184

Answers (3)

brso05
brso05

Reputation: 13232

System.out.printf("You will be paying a total amount of $%.2f", (Math.round((payment * 100.0)) / 100.0) * months);

This should round to 2 decimal places. What it does is move the decimal place over 2 spots then round then move back 2 spots. If you don't want to use BigDecimal this will work if you still want to use primitive type double.

Upvotes: 0

Abhiroop Sarkar
Abhiroop Sarkar

Reputation: 2311

You can try this:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
double payment_rounded =Double.parseDouble( df.format(payment));

Now you have the variable payment_rounded as a double with 2 places of decimal. And you can use this variable in both cases.

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109597

Use BigDecimal instead of double. The notation is uglier. Use new BigDecimal("12.34") to let BigDecimal know the precision. The usage is much uglier as you need methods like add and multiply.

BTW in the database use DECIMALS too, to have a fixed precision, and not a floating point approximation.

For a reason, do a search.

Upvotes: 1

Related Questions