Search code examples
swift3decimal

How do I round the Decimal type?


Using Swift3 and still getting the hang of things. I'm using the Decimal type because it involves currency and I'm having a difficult time with getting the rounding to work. I've read through the NSDecimalNumberHandler documentation and the rounding function but don't quite understand how to get this to work. Essentially I just want all my Decimal types in this class to round to the hundredths spot when the calculation functions I've built run.

Can someone give me quick example of how to do this? Thanks!


Solution

  • Please check this :

    This is using NSDecimalNumber & NSDecimalNumberHandler :

    let decimalStr = NSDecimalNumber(string: "500.2595")
    let decimalStrHandler = NSDecimalNumberHandler(roundingMode: .plain, scale: 3, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
    let roundedVal = decimalStr.rounding(accordingToBehavior: decimalStrHandler)
    print(roundedVal) // prints 500.26
    

    This is using NumberFormatter & Decimal :

    extension Decimal {
        func roundDecimal() -> String {
            let formatter = NumberFormatter()
            formatter.minimumFractionDigits = 2
            return formatter.string(from: self as NSDecimalNumber)!
        }
    }
    

    You have to call like below :

    let decimalStr = Decimal(string: "500.2595")!
    print(decimalStr.roundDecimal()) // prints 500.26
    
    let decimalFloat = Decimal(floatLiteral: 500.2595)
    print(decimalFloat.roundDecimal())  // prints 500.26