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)"
}
}
The best way to do this is to create an
NSNumberFormatter
. (NumberFormatter
in Swift 3.) You can request currency and it will set up the string to follow the user's localization settings, which is useful.If you want to force a US-formatted dollars and cents string you can format it this way:
How to do it in Swift 4:
You can use this string initializer if you want to force the currency to $:
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.In addition to the
NumberFormatter
orString(format:)
discussed by others, you might want to consider usingDecimal
orNSDecimalNumber
and control the rounding yourself, thereby avoid floating point issues. If you're doing a simple tip calculator, that probably isn't necessary. But if you're doing something like adding up the tips at the end of the day, if you don't round the numbers and/or do your math using decimal numbers, you can introduce errors.So, go ahead and configure your formatter:
and then, use decimal numbers:
Where
Obviously, you can replace all the above "2 decimal place" references with whatever number is appropriate for the currency you are using (or possibly use a variable for the number of decimal places).
you can create an Extension for either string or Int, I would show an example with String
link to get all locale identifier
You can to convert like that: this func convert keep for you maximumFractionDigits whenever you want to do
i create it in class Model then when you call , you can accecpt it another class , like this