Skip to content

Instantly share code, notes, and snippets.

@AliSoftware
Created August 21, 2018 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AliSoftware/d2dd0e1bc3a7e71e5b8288a583c008f4 to your computer and use it in GitHub Desktop.
Save AliSoftware/d2dd0e1bc3a7e71e5b8288a583c008f4 to your computer and use it in GitHub Desktop.
JSON Rounding Behavior
func json(from dict: [String: Any]) -> String {
let jsonData = try! JSONSerialization.data(withJSONObject: dict, options: [])
let str = String(data: jsonData, encoding: .utf8)!
return str
}
struct Product {
var price: Double
var quantity: Int
var toJSON: String {
return json(from: ["price": price, "quantity": quantity])
}
}
let p1 = Product(price: 0.90, quantity: 3)
print(p1.toJSON) // {"price":0.90000000000000002,"quantity":3}
let p2 = Product(price: 0.99, quantity: 3)
print(p2.toJSON) // {"price":0.98999999999999999,"quantity":3}
extension Product {
var toRoundedJSON: String {
// Use a NSDecimalNumber, rounded with a NSDecimalNumberHandler, and use that in the dict instead of a Double
let currencyBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 2,
raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)
let formattedPriceDN = NSDecimalNumber(value: price).rounding(accordingToBehavior: currencyBehavior)
return json(from: ["price": formattedPriceDN, "quantity": quantity])
}
}
print(p1.toRoundedJSON) // {"price":0.9,"quantity":3}
print(p2.toRoundedJSON) // {"price":0.99,"quantity":3}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment