In NSDecimalNumber
there's a method to round the number, I.E.
let handler = NSDecimalNumberHandler(roundingMode: .plain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
let example: NSDecimalNumber = 1.345
let rounded: NSDecimalNumber = example.rounding(accordingToBehavior: handler)
Now I've switched to Decimal
and it doesn't seem to have the method to round the number like NSDecimalNumber
has. Should I cast it to NSDecimalNumber
and cast it back to Decimal
just to round things up or is there a better and more elegant way of rounding a Decimal
?
EDIT: made a better example
Decimal
has become an easy and concise way to handle decimal numbers in Swift 3, but if you want to control some rounding mode or rounding scale, you need to use NSDecimal...
functions.
See Decimals part.
var dexample: Decimal = 1.345
var drounded: Decimal = Decimal()
NSDecimalRound(&drounded, &dexample, 2, .plain)
print(drounded) //->1.35