1
var arr1: Array = [34, 8.7, "hello"]
var arr2: Array<Any> = [34, 8.7, "hello"]

println(arr1)
println(arr2)

[34, 8.699999999999999, hello] [34, 8.7, hello]

different result,anyone can explain it?

2
  • 3
    Floating point precision. The computer can represent numbers only to a certain precision. 8.7 and 8.6999999999999 are essentially the same, though I can only speculate why they are displayed differently. Commented Sep 17, 2014 at 13:48
  • As @vacawama has noted, you can simplify this question to "why do println(NSNumber(double: 8.7)) and println(Double(8.7)) give different results?" Commented Sep 17, 2014 at 15:50

1 Answer 1

4

In the case of arr1, since you didn't specify the type and you have Foundation imported, Swift made the array type [NSObject]. Then, the types of 34, 8.7, and "hello" are NSNumber, NSNumber, and NSString respectively.

For whatever reason, an NSNumber with a value of 8.7 prints as 8.699999999999999. Try this is a Playground:

var a: NSNumber = 8.7
println(a)            // prints 8.699999999999999

In arr2, the values have the types Int, Double, and String, so the 8.7 prints as you would expect:

var b: Double = 8.7
println(b)           // prints 8.7

As Matt Gibson states in the comments:

the output difference may be because NSNumber's description method formats the number as "%0.16g"; if you do NSString(format: "%0.16g", 8.7) gives you "8.699999999999999". I'm sure they're both just the same double "underneath".

To test the theory that they are the same number underneath, I did:

if (arr1[1] as NSNumber).doubleValue == (arr2[1] as Double) {
    println("same")
}

and this does indeed print "same".

Sign up to request clarification or add additional context in comments.

1 Comment

I think the output difference may be because NSNumber's description method formats the number as "%0.16g"; if you do NSString(format: "%0.16g", 8.7) gives you "8.699999999999999". I'm sure they're both just the same double "underneath".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.