Skip to content

Instantly share code, notes, and snippets.

@abhijithpp
Last active January 24, 2023 14:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhijithpp/1cc41b41a5d1c8f007da90f20bc0c65f to your computer and use it in GitHub Desktop.
Save abhijithpp/1cc41b41a5d1c8f007da90f20bc0c65f to your computer and use it in GitHub Desktop.
A property wrapper to round decimal value
@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
@devarshiEsoft
Copy link

Hi,
How can I use this with codable?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment