I\'m having the hardest time figuring out something that seems like it should be very simple. I need to accurately round an NSDecimalNumber to a particular number of decimal
I'm using this solution:
import Foundation
extension NSDecimalNumber {
public func round(_ decimals:Int) -> NSDecimalNumber {
return self.rounding(accordingToBehavior:
NSDecimalNumberHandler(roundingMode: .plain,
scale: Int16(decimals),
raiseOnExactness: false,
raiseOnOverflow: false,
raiseOnUnderflow: false,
raiseOnDivideByZero: false))
}
}
let amount = NSDecimalNumber(string: "123.456")
amount.round(2) --> 123.46
amount.round(1) --> 123.5
amount.round(0) --> 123
amount.round(-1) --> 120
amount.round(-2) --> 100