I have 2 functions that are converting string (decimal numbers passed as string) localized numbers, and vice versa. Here is the code:
static func localizedNumberForText(text: String) -> String {
let num = Double(text)
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 30;
if num != nil {
return formatter.string(from: num! as NSNumber)!
} else {
return text
}
}
static func stringFromLocalizedNumber(text: String) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 30;
let num = formatter.number(from: text)
if let number = num {
return String(describing: number)
} else {
return text
}
}
This works perfect with static values, but I have a challenge that while UITextField
is being edited I need to format localized string in a different way. This is the example that works:
- I have number 123456789 and it is localized fine with thousand separator at display time as following: 123.456.789
But when user inside UITextField
deletes last character from this string it becomes 123.456.78 and in function stringFromLocalizedNumber fails to get num
from text because formatted text is not correctly localized. Any idea how I can fix this issue?
What I want to achieve is, after user deletes a numeric character or adds one to remove localization that is incorrect and apply new one that correctly parses this string as a number.