1

I spent hours trying to find the problem but I didn't find it.

Here is the problem :

let n = 4.99/Float(1)
print("n : \(n)")
let n1 = Float(10000)*n
print("n1 : \(n1)")
let n2 = floor(n1)
print("n2 : \(n2)")
let n3 = Int(n1)
print("n3 : \(n3)")

The result in the console is :

n : 4.99
n1 : 49900.0
n2 : 49899.0
n3 : 49899.0

My question is why n2 and n3 are equal to 49899. It should be equal to 49900.0

I tried to write

let n2 = floor(49900.0)

and it works perfectly. It shows me 49900.0. It's what I want.

I really don't know what I'm not doing good.

  • 2
    Add `print(String(format: "%.9f", n))` and you will see the issue. – rmaddy Apr 04 '18 at 16:39
  • 1
    And using `Double` instead of `Float` fixes this specific issue. – rmaddy Apr 04 '18 at 16:41
  • Using `Double` fixes it for this example, but there will be others where it will fail. – vacawama Apr 04 '18 at 16:42
  • Why is Float displaying it like this ? – David Goncalves Apr 04 '18 at 16:45
  • In short, floating point numbers are approximations. The internal representation is binary, so values like `0.1` do not have an exact representation. `Float` uses 32-bits to represent a number, and `Double` uses 64 bits. So `Double` does a better job, but it is still an approximation. `4.99` as a `Float` is stored as `4.9899997711181640625`, so it is slightly less than you expect. When you multiply by `10000`, it becomes `49899.99609375` and `floor` drops the fraction leaving `49899`. For `Double` `4.99` is represented as `4.99000000000000021316282072803` so it is larger than `4.99`. – vacawama Apr 04 '18 at 17:37
  • `Double` doesn't eliminate the problem. You will still find examples where it doesn't perform as you expect. – vacawama Apr 04 '18 at 17:40

0 Answers0