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?
By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in 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.
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.
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
let decimalToInt = (yourDecimal as NSDecimalNumber).intValue
or as @MartinR suggested:
let decimalToInt = NSDecimalNumber(decimal: yourDecimal).intValue
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