Skip to content

Instantly share code, notes, and snippets.

@kirsteins
Last active September 29, 2022 07:45
Show Gist options
  • Save kirsteins/46037fbd5892662ea7d0744ed91fff4c to your computer and use it in GitHub Desktop.
Save kirsteins/46037fbd5892662ea7d0744ed91fff4c to your computer and use it in GitHub Desktop.
Rounding to decimal places with correct decimal seperator for locale
extension NSDecimalNumber {
func round(decimalPlaces: Int, roundingMode: RoundingMode) -> NSDecimalNumber {
let handler = NSDecimalNumberHandler(
roundingMode: roundingMode,
scale: Int16(decimalPlaces),
raiseOnExactness: false,
raiseOnOverflow: false,
raiseOnUnderflow: false,
raiseOnDivideByZero: false)
return rounding(accordingToBehavior: handler)
}
}
extension Package {
func priceStringDividedBy(number: Double) -> String {
assert(number != 0)
return storeProduct
.priceDecimalNumber
.dividing(by: NSDecimalNumber(value: number))
.round(decimalPlaces: 2, roundingMode: .up)
.description(withLocale: Locale.current)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment