I have the following problem with iOS calculations when the user is in different locales. Here in Europe the decimal point separator is a "," and in other locales it might be a ".". As long as the user is in a locale with a "." all calculations work fine, but when a comma is used instead I get an error. Here's the simple code so far:
if let expense = expenseTextField.text
let expenseValue = Double(expense)
let guests = guestTextField.text
let guestValue = Double(guests) {
let result = round((expenseValue / guestValue) * 100) / 100
resultLabel.text = priceString
//resultLabel.text = String(result)
} else {
resultLabel.text = "No values!"
}
I am pretty sure I have to use the numberFormatter as far as I understand other questions on here, but I don't get how to do this and the documentation doesn't provide a sample how to create a double or float from a string. I tried the following but I get an error stating that I cannot neither create doubles nor use these variables for calculations:
if let expense = expenseTextField.text
let expenseValue = String(expense),
let guests = guestTextField.text
let guestValue = String(guests) {
let expenseFormatter = NumberFormatter()
expenseFormatter.number(from: expenseValue)
let guestFormatter = NumberFormatter()
guestFormatter.number(from: guestValue)
let expenseDouble = Double(expenseFormatter)
let guestDouble = Double(guestFormatter)
let result = round((expenseDouble / guestDouble) * 100) / 100
resultLabel.text = priceString
} else {
resultLabel.text = "No values!"
}
I am not sure how to create real Doubles from those strings with numberFormatter and then use them in calculations.
Can someone give me a tip? Thanks
The only thing you need is to write the method call correctly:
A formatter/parser directly converts string to
number. You then have to take theDoublevalue from it. Note that parsing can fail and you have to solve the resulting optional in that case, e.g. using?? 0.