1

i have below code in playground

let a:Double = 5.2
let b:Double = 5.3
print(b-a)

if data type is double the result is 0.0999999999999996 but if data type is float then result is 0.1.please explain why ?

iOSGuy
  • 171
  • 1
  • 14
  • I have tried 0.1+0.2 but it does not print such long value as 0.30000000000000004 – iOSGuy Jan 06 '17 at 11:48
  • I am using swift not javascript – iOSGuy Jan 06 '17 at 11:49
  • 1
    The issue is not language specific. Swift uses a binary floating point representation and arithmetic according to the IEEE 754 standard (as does JavaScript and many other languages). As explained in the linked-to thread, these values *cannot* represent all numbers exactly. Try `print(a.debugDescription, b.debugDescription, (b - a).debugDescription)` to see that `a` is not exactly 5.2, `b` is not `5.3`, and `b-a` is not `0.1`, for both `Double` and `Float`. – Martin R Jan 06 '17 at 12:02
  • I think this questions gets asked every day? – twiz_ Jan 06 '17 at 17:44
  • Computers represent numbers in binary. Both 5.2 and 5.3 can be represented precisely in decimal, but not in binary (5.2 in binary is 101.00110011001100... and 5.3 is 101.01001100110011...). Double uses a 64 bit representation, Float uses a 32-bit representation, so the rounding errors are different. – closetCoder Jan 06 '17 at 19:07
  • So how can i get same result as 0.1 with double also.As of now it is showing me result as 0.9999 something – iOSGuy Jan 09 '17 at 04:45
  • But in case of Float i get 0.1 not in Double – iOSGuy Jan 09 '17 at 05:09

0 Answers0