Hi I'm new to Java programing and I am having some trouble with doubles. I am trying to subtract .2 from 4.6 but instead of receiving 4.4 i get 4.3999999999999995. I know that Decimals can't be represented exactly in binary but is there any way around this problem. Any advice would be appreciated.
Asked
Active
Viewed 88 times
-1
-
3Learn to use the `BigDecimal` class instead of `double`. – Dawood ibn Kareem Nov 24 '14 at 22:12
-
2Or use `DecimalFormat` to present the output, or `printf().` – user207421 Nov 24 '14 at 22:13
-
For a quick fix, you could use `float` instead: `System.out.println(4.6F - 0.2F);`, but try to get familiar with `BigDecimal` since it is the better choice. – Tom Nov 24 '14 at 22:17
-
@Tom, BigDecimal is the better choice for certain problems (esp. financial calculations.) BigDecimal is _not_ what you want for most scientific calculations, for most physical modelling, for 3D graphics, or pretty much anything else that is modeled with _real number_ math. – Solomon Slow Nov 24 '14 at 22:26
-
Don't use `float` instead. The problem is worse with `float` than with `double`. – Dawood ibn Kareem Nov 24 '14 at 22:31
-
1Re, "is there any way around this problem." Depends what the "problem" is. If the problem is that you don't like seeing so many digits after the decimal point in a printout or an output file, then the solution is to do what @EJP said, and format the number as you like it. If, on the other hand, the sixteenth decimal place actually matters in the math that you're doing, then you may want to do what everybody else says and use BigDecimal. But be aware, BigDecimal is _not_ a replacement for `double`. They each have their uses, and there's not as much overlap as some people think. – Solomon Slow Nov 24 '14 at 22:31
2 Answers
1
You could use BigDecimal
or you could use formatted output like
System.out.printf("%.2f%n", 4.6 - 0.2);
Output is
4.40
Or, using BigDecimal
BigDecimal bd = BigDecimal.valueOf(4.6);
System.out.println(bd.subtract(BigDecimal.valueOf(0.2)));
Output is
4.4

Elliott Frisch
- 198,278
- 20
- 158
- 249
1
If you use the BigDecimal
class in place of double
, you won't get this imprecision. Note that when you create a BigDecimal
, it's best to pass in the value as a String
, so that there's never any rounding.
BigDecimal first = new BigDecimal("4.6");
BigDecimal second = new BigDecimal("0.2");
System.out.println(first.subtract(second));

Dawood ibn Kareem
- 77,785
- 15
- 98
- 110