Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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}
Add Comment
Please, Sign In to add comment