Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal to Double conversion in Swift 3

I'm migrating a project from Swift 2.2 to Swift 3, and I'm trying to get rid of old Cocoa data types when possible.

My problem is here: migrating NSDecimalNumber to Decimal.

I used to bridge NSDecimalNumber to Double both ways in Swift 2.2:

let double = 3.14 let decimalNumber = NSDecimalNumber(value: double)  let doubleFromDecimal = decimalNumber.doubleValue 

Now, switching to Swift 3:

let double = 3.14 let decimal = Decimal(double)  let doubleFromDecimal = ??? 

decimal.doubleValue does not exist, nor Double(decimal), not even decimal as Double... The only hack I come up with is:

let doubleFromDecimal = (decimal as NSDecimalNumber).doubleValue 

But that would be completely stupid to try to get rid of NSDecimalNumber, and have to use it once in a while...

Well, either I missed something obvious, and I beg your pardon for wasting your time, or there's a loophole needed to be addressed, in my opinion...

Thanks in advance for your help.

Edit : Nothing more on the subject on Swift 4.

Edit : Nothing more on the subject on Swift 5.

like image 847
Zaphod Avatar asked Oct 06 '16 08:10

Zaphod


People also ask

How do you round to 2 decimal places in Swift?

By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.

What is decimal type in Swift?

In Swift, there are two types of floating-point number, both of which are signed. These are the Float type which represents 32-bit floating point numbers with at least 6 decimal digits of precision and the Double type which represents 64-bit floating point numbers at least 15 decimal digits of precision.

How do you round off in Swift?

Swift provide a built-in function named as ceil() function. This function is used to round the given number to the nearest smallest integer value which is greater than or equal to the given number. It accept also both Float and Double.


1 Answers

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 
like image 153
sketchyTech Avatar answered Sep 25 '22 14:09

sketchyTech