mallow
mallow

Reputation: 2836

How to get an absolute value from NSDecimalNumber?

How to get an absolute value from NSDecimalNumber? Getting absolute value from Integer is easy, but I need one from NSDecimalNumber. I have found answers from few years ago (Objective-C, for example), but I was hoping that in Swift in 2020 it is easier now.

Code from my playground:

import UIKit

var str = "Hello, playground"

// absolute value

let intValue: Int = -5
let absoluteIntValue = abs(intValue) // works
print("\(absoluteIntValue)") // 5

let value: NSDecimalNumber = -5.234
let absoluteValue = abs(value) // doesn't work. Gives an error: Cannot convert value of type 'NSDecimalNumber' to expected argument type 'Int32'
print("\(absoluteValue)")

Upvotes: 1

Views: 988

Answers (1)

vadian
vadian

Reputation: 285069

Just replace NSDecimalNumber with (native) Decimal. The generic abs function considers also the Decimal type

let value: Decimal = -5.234
let absoluteValue = abs(value) 
print(absoluteValue)

Upvotes: 2

Related Questions