I'm trying to calculate a percentage(9% tax) of a item
double amount = 55.4;
double total = amount * 0.09;
System.out.printf ("%f \n", total);
System.out.printf ("%.2f \n", total);
Returns
4.986000
4.99
How do I make it return 4.98?
Thanks!
I'm trying to calculate a percentage(9% tax) of a item
double amount = 55.4;
double total = amount * 0.09;
System.out.printf ("%f \n", total);
System.out.printf ("%.2f \n", total);
Returns
4.986000
4.99
How do I make it return 4.98?
Thanks!
Use BigDecimal instead of double.
double is floating point, which cannot accurately represent all fractional amounts, hence the "rounding" problem that you are.experiencing.
BigDecimal is arbitrary-precision, and so doesn't have that problem.
If you want to chop off the thousands place multiple your total by 100 and cast it to an int, then divide it by 100 and cast it to a double:
double amount = 55.4;
double total = amount * 0.09;
int truncated = (int) (total * 100);
double val = truncated * .01;
System.out.printf("%.2f\n", val);
This will give you: 4.98
This can also be done with
double val = Math.floor(total * 100) / 100;
System.out.printf("%.2f\n", val);