Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 : Decimal to Int

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?

like image 666
Colin Wang Avatar asked Sep 27 '16 17:09

Colin Wang


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.

Can int have decimals Swift?

Second, Swift considers decimals to be a wholly different type of data to integers, which means you can't mix them together. After all, integers are always 100% accurate, whereas decimals are not, so Swift won't let you put the two of them together unless you specifically ask for it to happen.

What is a decimal 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.


2 Answers

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 
like image 168
tech4242 Avatar answered Sep 20 '22 14:09

tech4242


let decimalToInt = (yourDecimal as NSDecimalNumber).intValue 

or as @MartinR suggested:

let decimalToInt = NSDecimalNumber(decimal: yourDecimal).intValue 
like image 36
Juan Boero Avatar answered Sep 18 '22 14:09

Juan Boero