From db224f8d77393f131a154da484be0c4adf21000f Mon Sep 17 00:00:00 2001 From: Jonathan Tsai Date: Thu, 28 Aug 2014 18:47:39 -0700 Subject: [PATCH] format currency according to the locale - use NSNumberFormatter to automatically handle currency symbol, thousands/decimal separator not reformatting when switching out/back into the app, only when view reloads --- tips/Base.lproj/Main.storyboard | 3 +-- tips/TipsViewController.swift | 8 ++++---- tips/Utils.swift | 7 +++++++ 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/tips/Base.lproj/Main.storyboard b/tips/Base.lproj/Main.storyboard index fc3c12f..761a23a 100644 --- a/tips/Base.lproj/Main.storyboard +++ b/tips/Base.lproj/Main.storyboard @@ -1,7 +1,6 @@ - @@ -146,7 +145,7 @@ - + diff --git a/tips/TipsViewController.swift b/tips/TipsViewController.swift index 96f2bb9..614dc05 100644 --- a/tips/TipsViewController.swift +++ b/tips/TipsViewController.swift @@ -18,8 +18,8 @@ class TipsViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. - tipLabel.text = "$0.00" - totalLabel.text = "$0.00" + tipLabel.text = formatCurrency(0.0) + totalLabel.text = formatCurrency(0.0) } override func viewWillAppear(animated: Bool) { @@ -71,8 +71,8 @@ class TipsViewController: UIViewController { if (wasEdited) { storeLastBillAmount(billAmount) } - tipLabel.text = String(format: "$%.2f", tip) - totalLabel.text = String(format: "$%.2f", total) + tipLabel.text = formatCurrency(tip) + totalLabel.text = formatCurrency(total) } } diff --git a/tips/Utils.swift b/tips/Utils.swift index 65fe6c7..1e00b81 100644 --- a/tips/Utils.swift +++ b/tips/Utils.swift @@ -19,3 +19,10 @@ func getDefaults(key: String) -> AnyObject? { var value: AnyObject? = defaults.objectForKey(key) return value } + +func formatCurrency(amount: Double) -> String { + var numberFormatter = NSNumberFormatter() + numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle + var formattedAmount = numberFormatter.stringFromNumber(amount) + return formattedAmount +}