0

How to calculate doubles accurately in Swift? I try it on Swift playground, and 10.0 - 0.2 won't be 9.8. How to fix it?

enter image description here

Howard
  • 601
  • 1
  • 11
  • 15
  • Read this, it's enlightening: http://floating-point-gui.de/ – Eric Aya Mar 17 '16 at 15:32
  • It is a (well-known) fact that binary floating point numbers cannot represent all values exactly. [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) is an enlightening thread around that issue. – Martin R Mar 17 '16 at 15:50
  • And of course: ["What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Martin R Mar 17 '16 at 15:51
  • @EricD. I know Floating-Point Arithmetic, but we have library like https://github.com/MikeMcl/decimal.js/ in Javascript to solve these problems. Is there similar thing in Swift? – Howard Mar 17 '16 at 16:25
  • @Howard: NSDecimalNumber. – Martin R Mar 17 '16 at 16:28
  • @MartinR http://i.imgur.com/AxsiXgU.png Still no luck. – Howard Mar 17 '16 at 16:33

1 Answers1

0

You could use round. So for your example this should work:

let x = 10.0 - 0.2
let y = Double(round(100*x)/100)

If you want more accuracy multiply and divide for example by 1000 or 10000 and so on.

Daskus
  • 929
  • 1
  • 10
  • 25