1

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?

slimboy
  • 1,633
  • 2
  • 22
  • 45
  • It seems to be working just fine http://swiftlang.ng.bluemix.net/#/repl/57acc49a603420ce5f482bb3 – Alexander Aug 11 '16 at 18:32
  • Is `timestamp` a string? – jscs Aug 11 '16 at 18:33
  • No, it's an NSNumber, It's really confusing why it's doing that – slimboy Aug 11 '16 at 18:39
  • @AlexanderMomchliov I tried it with 6 decimal places and it rounded to 5 – slimboy Aug 11 '16 at 18:44
  • @slimboy What input did you try, what output did you get, and what did you expect? – Alexander Aug 11 '16 at 18:46
  • @AlexanderMomchliov using the values you offered yourself on: [link] (swiftlang.ng.bluemix.net/#/repl/57acc49a603420ce5f482bb3) I get Input: let input: NSNumber = 1470938337.572778 Output: 1470938337.57278 The last 6th decimal is rounded. I need to use the timestamp as an ID so it must remain 6 when converting to double – slimboy Aug 11 '16 at 18:50
  • @slimboy Take a careful look at [this.](http://swiftlang.ng.bluemix.net/#/repl/57acc9bf603420ce5f482bb7). The literal value being assigned to `input` is `1470938337.572778`. What's printed (even whilst still in `NSNumber` form) is `1,470,938,337.57278`. – Alexander Aug 11 '16 at 18:55
  • This is a case of exceeding the precision representable by an IEEE754 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`). – Alexander Aug 11 '16 at 18:56
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/120735/discussion-between-alexander-momchliov-and-slimboy). – Alexander Aug 11 '16 at 18:58

1 Answers1

1

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

ospahiu
  • 3,465
  • 2
  • 13
  • 24
Alexander
  • 59,041
  • 12
  • 98
  • 151