Guest User

Untitled

a guest
Aug 21st, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. func json(from dict: [String: Any]) -> String {
  2. let jsonData = try! JSONSerialization.data(withJSONObject: dict, options: [])
  3. let str = String(data: jsonData, encoding: .utf8)!
  4. return str
  5. }
  6.  
  7. struct Product {
  8. var price: Double
  9. var quantity: Int
  10.  
  11. var toJSON: String {
  12. return json(from: ["price": price, "quantity": quantity])
  13. }
  14. }
  15.  
  16. let p1 = Product(price: 0.90, quantity: 3)
  17. print(p1.toJSON) // {"price":0.90000000000000002,"quantity":3}
  18. let p2 = Product(price: 0.99, quantity: 3)
  19. print(p2.toJSON) // {"price":0.98999999999999999,"quantity":3}
  20.  
  21. extension Product {
  22. var toRoundedJSON: String {
  23. // Use a NSDecimalNumber, rounded with a NSDecimalNumberHandler, and use that in the dict instead of a Double
  24. let currencyBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 2,
  25. raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)
  26. let formattedPriceDN = NSDecimalNumber(value: price).rounding(accordingToBehavior: currencyBehavior)
  27.  
  28. return json(from: ["price": formattedPriceDN, "quantity": quantity])
  29. }
  30. }
  31.  
  32. print(p1.toRoundedJSON) // {"price":0.9,"quantity":3}
  33. print(p2.toRoundedJSON) // {"price":0.99,"quantity":3}
Add Comment
Please, Sign In to add comment