slimboy slimboy - 2 months ago 9
Swift Question

Double is rounding my last NSNumber decimal

For example


gives me: 1470938337.572778


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?


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)")


   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).