If you need to work with true precision (for example, for currency-related applications), you probably want to use NSDecimalNumber instead of a floating point.
The above approach can be applied to NSDecimalNumbers, as shown below. In this example, the “step” that you round can be whatever you select, just set the “increment” accordingly.
let number: NSDecimalNumber = 100.52 let increment: NSDecimalNumber = 0.25 let handler = NSDecimalNumberHandler(roundingMode: NSRoundingMode.RoundBankers, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) // Rounds to the nearest whole number let result = number.decimalNumberByDividingBy(increment).decimalNumberByRoundingAccordingToBehavior(handler).decimalNumberByMultiplyingBy(increment)
For more information on rounding with NSDecimalNumber see here: How to combine NSDecimalNumber in swift?
And yes, working with NSDecimalNumber is an awfully detailed way to do the math, but it's not complicated. If you often carry out a project with their participation, I recommend that you consider creating extensions to the Swift operator so that you can manage them more efficiently. Check out a good example: https://gist.github.com/mattt/1ed12090d7c89f36fd28
Rgood
source share