Diljot Jawanda - 1 year ago 61

Swift Question

Trying to output the total of three number values from a dictionary and then adding HST of 13% to the total. However, the calculations print out as **$13.5261** with four decimals places. How do I cut out the end decimal places, so it's $13.52? Or is there a way to round it, so it's $13.53

import UIKit

var menu = ["Coke": 1.99, "Coffee": 3.99, "Water": 5.99]

var hst = 1.13

var total = hst * (menu["Coke"]! + menu["Coffee"]! + menu["Water"]!)

print("The total for your order is

$(total)")

Answer

The usual – and most versatile – way is `NSNumberFormatter`

```
let menu = ["Coke": 1.99, "Coffee": 3.99, "Water": 5.99]
let hst = 1.13
let total = hst * (menu["Coke"]! + menu["Coffee"]! + menu["Water"]!)
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 2
let roundedTotal = formatter.stringFromNumber(total)!
print("The total for your order is $\(roundedTotal)")
```

Source (Stackoverflow)