I have a project where I receive a cost of a product and the amount paid. I need to derive the smallest amount of coins that will make the change. I use double variables for the price and the paid amount, as well as the change: double change = double paidAmount-double cost; My problem is that for 1 - 0.66 I receive 0.33999998 instead of 0.34 What type of variables should I use to get exactly two digit after the floating point result? Please not that I must not use BigNumber
Asked
Active
Viewed 38 times
1 Answers
0
Please try DecimalFormat format double
double change = 1 - 0.66;
double result = Double.parseDouble(new DecimalFormat("#.00").format(change));
System.out.println(result);
0.34

verejava
- 7
- 5
-
It would be better to just use `BigDecimal` everywhere, so that the value being represented is the *exact* value desired. – Jon Skeet Jun 03 '19 at 11:00
-
@Jekozo said : Please not that I must not use BigNumber – verejava Jun 03 '19 at 11:01
-
Technically `BigDecimal` doesn't use `BigNumber` since that isn't a class... – BeUndead Jun 03 '19 at 11:20