I've been searching for a clean and correct way to convert an NSDecimalNumber
retrieved from CoreData
to a Double.
I'm looking for a recommendation on how to do this. I need to take 2 decimal numbers from my CoreData
and calculate a percentage to use in a progress bar etc.
Floating-Point Numbers Swift provides two signed floating-point number types: Double represents a 64-bit floating-point number. Float represents a 32-bit floating-point number.
NSDecimalNumber , an immutable subclass of NSNumber , provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.
NSDecimalNumber has a property var doubleValue: Double { get }
. So you can say num.doubleValue
.
For division of two NSDecimalNumbers you should use num1.dividing(by: num2)
.
Keep in mind that in Swift you can also use Decimal
which supports +
, *
, /
, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With