Converting NSDecimalNumber to Int

Hi, I was using pow in my code and noticed that it returns decimal type. As I had to further use this value in different calculations, I was looking into converting this to Int type.

I did this by wrapping it with NSDecimalNumber and then Int as follows; Int(NSDecimalNumber(decimal: pow(10,i))).

However, this is giving me a warning

warning: 'init(_:)' is deprecated: replaced by 'init(truncating:)'

and a note during compilation and execution

note: use 'init(truncating:)' instead
                recreated_n += digits[i-len]*Int(NSDecimalNumber(decimal: pow(10,i)))

I just wanted know if there's a better way to do this.


There's more than one pow function, but the only one that takes an Int as its second argument is

func pow(_ x: Decimal, _ y: Int) -> Decimal

So assuming you want the result to be an Int and your i is an Int in the range 0 ... 18, you can do eg the following (using the pow that takes two Doubles):

let tenToThePowerOfI = Int(pow(10, Double(i)))

Note that 1019 is greater than Int.max so depending on your actual use case, this might not be what you want.

pow is heavily overloaded. There are overloads that don't return a decimal:

public func pow(_ lhs: Float, _ rhs: Float) -> Float
public func pow(_ lhs: Float80, _ rhs: Float80) -> Float80
public func pow(_: Double, _: Double) -> Double
public func pow(_ lhs: CGFloat, _ rhs: CGFloat) -> CGFloat
public func pow(_ x: Decimal, _ y: Int) -> Decimal
Terms of Service

Privacy Policy

Cookie Policy