-2

Possible Duplicate:
Android number format is wrong somehow, instead of 3.5 I get 3.499999999, why?

Does any one know why Android platform gives such strange result?

4.1 - 4 = 0.09999999999999964

It's only 4 that gives such strange rounding.

Actually I need to get mantissa from 4.1 so I need 0.1 as result but not 0.09999999999999964.

Any ideas?

Community
  • 1
  • 1
Anton
  • 1,001
  • 9
  • 23
  • 1
    you should research floating point operations, and number formatting. – Julian Higginson Jul 17 '12 at 13:07
  • You should use `BigDecimal` for this kind of operations, if you want the exact calculation. – Lion Jul 17 '12 at 13:08
  • 3
    Guys, if you're giving minus. Please explain to Anton. @Anton, if you're working with money it's better to use another datatype from Double and Float – Eugen Martynov Jul 17 '12 at 13:08
  • 1
    also, it is NOT true that ONLY 4 gives this kind of result. I think that `0.09999999999999964` is the closest aproximation of 0.1 for floats – Rafael T Jul 17 '12 at 13:14
  • To do fixed-precision math in many languages you should multiply by a power of ten, then after the calculation, divide by the same power of ten. The quotient is the integer portion of the result. The remainder is the fractional portion. If you want variable precision in the calculation, but fixed precision for the output, use floating point types and NumberFormat to print it. – John Watts Jul 17 '12 at 13:17
  • `BigDecimal c = new BigDecimal("4.1").subtract(new BigDecimal("4")); double d = c.doubleValue();` This would give you **0.1** – waqaslam Jul 17 '12 at 13:38

1 Answers1

1

This is an issue of rounding. You can take a look at the BigDecimal class which should do what you need.

npinti
  • 51,780
  • 5
  • 72
  • 96
  • For example: `BigDecimal c = new BigDecimal("4.1").subtract(new BigDecimal("4")); double d = c.doubleValue();` – waqaslam Jul 17 '12 at 13:39
  • Thanks, but nope, it does not do the trick. The result of such construction is also 0.09999999999999964. – Anton Jul 21 '12 at 14:14