Last active
January 24, 2023 14:07
-
-
Save abhijithpp/1cc41b41a5d1c8f007da90f20bc0c65f to your computer and use it in GitHub Desktop.
A property wrapper to round decimal value
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
@propertyWrapper | |
struct Rounded { | |
private(set) var value: Decimal = 0.0 | |
let rule: NSDecimalNumber.RoundingMode | |
let scale: Int | |
var wrappedValue: Decimal { | |
get { value } | |
set { value = roundedDecimal(value:newValue,scale: scale, mode: rule) } | |
} | |
private func roundedDecimal(value:Decimal, scale: Int = 0, mode: NSDecimalNumber.RoundingMode) -> Decimal { | |
var result = Decimal() | |
var valueToChange = value | |
NSDecimalRound(&result, &valueToChange, scale, mode) | |
return result | |
} | |
} | |
// Example | |
struct GameResult { | |
@Rounded(rule: NSDecimalNumber.RoundingMode.up,scale: 4) | |
var score: Decimal | |
} | |
var result = GameResult() | |
result.score = 3.14159265358979 | |
print(result.score) // 3.1416 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
How can I use this with codable?