Decimal to Double conversion in Swift 3
Solution 1:
NSDecimalNumber
and Decimal
are bridged
The Swift overlay to the Foundation framework provides the Decimal structure, which bridges to the NSDecimalNumber class. The Decimal value type offers the same functionality as the NSDecimalNumber reference type, and the two can be used interchangeably in Swift code that interacts with Objective-C APIs. This behavior is similar to how Swift bridges standard string, numeric, and collection types to their corresponding Foundation classes. Apple Docs
but as with some other bridged types certain elements are missing.
To regain the functionality you could write an extension:
extension Decimal {
var doubleValue:Double {
return NSDecimalNumber(decimal:self).doubleValue
}
}
// implementation
let d = Decimal(floatLiteral: 10.65)
d.doubleValue
Solution 2:
Another solution that works in Swift 3 is to cast the Decimal
to NSNumber
and create the Double
from that.
let someDouble = Double(someDecimal as NSNumber)
As of Swift 4.2 you need:
let someDouble = Double(truncating: someDecimal as NSNumber)
Solution 3:
Solution that works in Swift 4
let double = 3.14
let decimal = Decimal(double)
let doubleFromDecimal = NSDecimalNumber(decimal: decimal).doubleValue
print(doubleFromDecimal)