slimboy slimboy - 3 months ago 12
Swift Question

Double is rounding my last NSNumber decimal

For example

print(message.timestamp!)


gives me: 1470938337.572778

print(Double(message.timestamp!))


gives me: 1470938337.57278

I need to use the double to convert to NSDate like this:

date: NSDate(timeIntervalSince1970: Double(message.timestamp!))


but I also need the timestamps to be accurate why is it rounding?

Answer

Take a look at this sample code:

import Foundation

let input: NSNumber = 1470938337.572778

print("   NSNumber: \(input)")
print("     Double: \(Double(input))")
print("doubleValue: \(input.doubleValue)")

Output:

   NSNumber: 1,470,938,337.57278 //not even this is printing correctly.
     Double: 1470938337.57278
doubleValue: 1470938337.57278

This is a case of exceeding the precision representable by an IEEE 754 Double width floating point data type. The issue isn't in the NSNumber -> Double conversion (which makes sense, because NSNumber is a wrapper for a Double).

Comments