Swift 3 : Decimal to Int

Go To StackoverFlow.com

19

I tried to convert Decimal to Int with the follow code:

Int(pow(Decimal(size), 2) - 1) 

But I get:

.swift:254:43: Cannot invoke initializer for type 'Int' with an argument list of type '(Decimal)' 

Here I know pow is returning a Decimal but it seems that Int has no constructors and member functions to convert Decimal to Int.
How can I convert Decimal to Int in Swift 3?

2016-09-27 17:51
by Colin Witkamp
Use Decimal only for currency values. Except that use double or float - Mr. A 2016-09-27 18:04
NSDecimalNumber(decimal: yourDecimal).intValue should work - Martin R 2016-09-27 18:35
Why did you say Decimal(size) to begin with - matt 2016-09-27 19:30


22

This is my updated answer (thanks to Martin R and the OP for the remarks). The OP's problem was just casting the pow(x: Decimal,y: Int) -> Decimal function to an Int after subtracting 1 from the result. I have answered the question with the help of this SO post for NSDecimal and Apple's documentation on Decimal. You have to convert your result to an NSDecimalNumber, which can in turn be casted into an Int:

let size = Decimal(2)
let test = pow(size, 2) - 1
let result = NSDecimalNumber(decimal: test)
print(Int(result)) // testing the cast to Int
2016-09-27 17:59
by tech4242
I just wanted to know how to convert Decimal to Int, unfortunately you misunderstood my goal - Colin Witkamp 2016-09-27 18:12
There is a pow(_ x: Decimal, _ y: Int) -> Decimal function - Martin R 2016-09-27 18:37
Awesome! That works - Colin Witkamp 2016-09-28 02:36


9

let decimalToInt = (yourDecimal as NSDecimalNumber).intValue

or as @MartinR suggested:

let decimalToInt = NSDecimalNumber(decimal: yourDecimal).intValue
2018-02-20 14:20
by Juan Boero
Ads