Last active
September 29, 2022 07:45
-
-
Save kirsteins/46037fbd5892662ea7d0744ed91fff4c to your computer and use it in GitHub Desktop.
Rounding to decimal places with correct decimal seperator for locale
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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