how do I convert a Decimal to an Int?

Generated on 7/30/2024

1 search

To convert a Decimal to an Int in Swift, you can use the NSDecimalNumber class, which provides a method to convert to an integer. Here is an example:

import Foundation

let decimalNumber = Decimal(10.5)
let intValue = NSDecimalNumber(decimal: decimalNumber).intValue
print(intValue) // Output: 10

This code snippet demonstrates how to convert a Decimal to an Int by first creating an NSDecimalNumber from the Decimal and then using the intValue property to get the integer value.

For more detailed information on handling types in Swift, you might find the session Consume noncopyable types in Swift useful.