Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a Double into Currency - Swift 3

I'm new to Swift programming and I've been creating a simple tip calculator app in Xcode 8.2, I have my calculations set up within my IBAction below. But when I actually run my app and input an amount to calculate (such as 23.45), it comes up with more than 2 decimal places. How do I format it to .currency in this case?

@IBAction func calculateButtonTapped(_ sender: Any) {      var tipPercentage: Double {          if tipAmountSegmentedControl.selectedSegmentIndex == 0 {             return 0.05         } else if tipAmountSegmentedControl.selectedSegmentIndex == 1 {             return 0.10         } else {             return 0.2         }     }      let billAmount: Double? = Double(userInputTextField.text!)      if let billAmount = billAmount {         let tipAmount = billAmount * tipPercentage         let totalBillAmount = billAmount + tipAmount          tipAmountLabel.text = "Tip Amount: $\(tipAmount)"         totalBillAmountLabel.text = "Total Bill Amount: $\(totalBillAmount)"     } } 
like image 348
Gar Avatar asked Jan 09 '17 23:01

Gar


People also ask

How do you round a string in Swift?

The "%f" format string means "a floating point number," but "%. 2f" means "a floating-point number with two digits after the decimal point. When you use this initializer, Swift will automatically round the final digit as needed based on the following number.


1 Answers

You can use this string initializer if you want to force the currency to $:

String(format: "Tip Amount: $%.02f", tipAmount) 

If you want it to be fully dependent on the locale settings of the device, you should use a NumberFormatter. This will take into account the number of decimal places for the currency as well as positioning the currency symbol correctly. E.g. the double value 2.4 will return "2,40 €" for the es_ES locale and "¥ 2" for the jp_JP locale.

let formatter = NumberFormatter() formatter.locale = Locale.current // Change this to another locale if you want to force a specific locale, otherwise this is redundant as the current locale is the default already formatter.numberStyle = .currency if let formattedTipAmount = formatter.string(from: tipAmount as NSNumber) {     tipAmountLabel.text = "Tip Amount: \(formattedTipAmount)" } 
like image 94
silicon_valley Avatar answered Sep 22 '22 19:09

silicon_valley