0

My basic maths tells me: 4.0/10.0 == 0.4

But in swift, I get:

4.0/10.0
> Double = 0.40000000000000002

What is the cause of this weirdness? How do I get the number I expected?

picciano
  • 22,341
  • 9
  • 69
  • 82
user3574603
  • 3,364
  • 3
  • 24
  • 59
  • It's because of the imprecision of Double values. The same applies to Float. – Andreas is moving to Codidact Feb 05 '18 at 10:33
  • 2
    Have a look at [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – that applies to all binary floating point arithmetic. – Martin R Feb 05 '18 at 10:33
  • 3
    And of course: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Martin R Feb 05 '18 at 10:35
  • let num1:Double = 4.0 let num2:Double = 10.0 var num3 = num1/num2 print(num3) – Muhammad Shauket Feb 05 '18 at 10:50
  • If you have a problem that you think can be solved with floating point arithmetic, you just risk creating 2.00000000000832 problems. – picciano Feb 05 '18 at 15:36

0 Answers0