Number formatter not allowing decimals to show - ios

Here is the obligatory "I'm new to programming" but, I've searched all available answers and have concluded that my issue may be more logic related than code, but I could be wrong about that too. I'm building a calculator app and everything is working except the numberFormatter (to show comma separators) in the display. Whenever I try to format the number in the display, I can't get the display to show the decimal and the commas.
If I start with a decimal .1234 , I get 0.1234 and if I type 12345 I get 12,345 but if i type 12345.678, I get 12,345. I'm losing the decimals. I've tested it and my function to remove extraneous "." doesn't seem to be the issue. And If I run the string extension numberFormatter outside of the label formatting controls it seems to work, but I need to guard against multiple decimals and extraneous "0"s.
I'm showing the code to the IBAction covering the buttons showing up on the display label, display.text which is the issue. All calculations after this are working fine, with the replacingOccurrences(of: ",", with: "") to create a clean string to convert to Double and calculate.
I'm using a sting extension to do the formatting. I've been working on and off on this for weeks. Any ideas? Do I have to refactor how I enter text into the label.text?
here is the code to add text to the UILabel display.
#IBAction func btnTouchDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
if isUserTyping {
var formattedNumber = ""
print( "is user typting + String\(isUserTyping)")
// make sure we aren't adding a second period
var textCurrentlyInDisplay = display.text
textCurrentlyInDisplay = textCurrentlyInDisplay?.replacingOccurrences(of: ",", with: "")
if digit == "." && ((textCurrentlyInDisplay?.range(of: ".")) != nil) {
return
}
else {
formattedNumber = (textCurrentlyInDisplay! + digit)
print("formattedNumber = \(formattedNumber.twoFractionDigits)")
display.text = formattedNumber.twoFractionDigits
// put code here to format label.text to show thousand seperators
print("textCurrentlyInDisplay end = \(textCurrentlyInDisplay!)")
}
}
// make sure we aren't entering a bunch of zero's
else { print("else + \(isUserTyping)")
display.text = digit
if digit == "0" {return}
else if digit == "." {display.text = "0."}
// display.text = (digit == "." ? "0" : "") + digit
isUserTyping = true
}
}
Here is my extension to handle the string conversion for the numberFormatter.
extension String {
var twoFractionDigits: String {
let styler = NumberFormatter()
styler.minimumFractionDigits = 0
styler.maximumFractionDigits = 16
styler.numberStyle = .decimal
let converter = NumberFormatter()
converter.decimalSeparator = "."
if let result = converter.number(from: self) {
return styler.string(from: result)!
}
return ""
}

I found a hack to work around my problem. It's not pretty, but it works. I was able to get the numberFormatter to update and show the digits after the decimal but that led to a new issue. If you typed 12345.00 you would get 12,344 and not see the trailing 0's until you pressed another number. ex 12345.1 -> 12,345.1, 12345.001 -> 12,345.001, but 12345.00 -> 12,345.
I needed it to work dynamically so the user knows how many zeros are being entered. My hack was to split the final amount into an two arrays. One pre-formatted and one post-formatted. Then join the two together for the final display number.
I'd still love to find a more efficient solution, if anyone has any ideas.
Here is the updated code.
#IBAction func btnTouchDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
if isUserTyping {
preFormattedNumber = (display.text?.replacingOccurrences(of: ",", with: ""))!
// set the limit for number of digits user can enter at once
if display.text!.count >= 16 {
return
}
else {
// make sure we aren't adding a second period
if digit == "." && ((preFormattedNumber.range(of: ".")) != nil) {
print("extra decimal pressed")
return
}
else {
preFormattedNumber = (preFormattedNumber + digit)
print("preFormattedNumber before Formatting = \(preFormattedNumber)")
}
// put code here to format label.text to show thousand seperators
if ((preFormattedNumber.range(of: ".")) != nil){
print("just checked for .")
let numPreFormat = preFormattedNumber
let numAfterFormat = preFormattedNumber.twoFractionDigits
let numArray = numPreFormat.components(separatedBy: ".")
let numArrayFormatted = numAfterFormat.components(separatedBy: ".")
let afterDecimal = numArray.last
let beforeDecimal = numArrayFormatted.first
let finalNumberToDisplay = beforeDecimal! + "." + afterDecimal!
print("numArray = \(numArray)")
print("final number to display = \(finalNumberToDisplay)")
print("numArray = \(numArray)")
display.text = finalNumberToDisplay
runningNumber = display.text!
}
else {
display.text = preFormattedNumber.twoFractionDigits
runningNumber = display.text!
}
}
}
// make sure we aren't entering a bunch of zero's
else { print("else + \(isUserTyping)")
preFormattedNumber = digit
display.text = preFormattedNumber
runningNumber = display.text!
if digit == "0" {return}
else if digit == "." { preFormattedNumber = "0.";
}
display.text = preFormattedNumber
runningNumber = display.text!
isUserTyping = true
}
}

Related

How to make Double number to add thousand mark and set minimumFractionDigits?

I have a question about number formatter.
I want to add thousand separator mark to my double number.
And I also to set it's minimumFractionDigits, but I failed.
func formatterNumberToString(_ numberText: String, digits: Int) -> String {
let str = numberText
let formatter = Formatter.withSeparator
formatter.minimumFractionDigits = digits
let finalStr = formatter.string(for: Double(str)!)
if let finalStr = finalStr {
return finalStr
} else {
return "none"
}
}
self.formatterNumberToString("10003232.234", digits: 2) //it return 10,003,232.234
Why minimumFractionDigits not work?
Your code is working fine. The condition for minimum number of digits is met. What you probably need is to always show 2 digits. So, just add this line,
formatter.maximumFractionDigits = digits
This will display
10,003,232.23

Ios Swift texfield change a ',' into a '.' [duplicate]

I'm using a textField which is filled from a numerical pad.
Trouble is that, with lot of local region formats (all european, for example), UITextField's numerical pad has comma instead dot, so everytime I write a decimal number, UITextField can't recognise the decimal comma and it round number; for example 23,07 become 23.
How can I solve this?
I thought to set the textField fixed on USA; is it possible? How?
I read the value using this:
var importo = (importoPrevistoTF.text as NSString).floatValue
Swift 4
extension String {
static let numberFormatter = NumberFormatter()
var doubleValue: Double {
String.numberFormatter.decimalSeparator = "."
if let result = String.numberFormatter.number(from: self) {
return result.doubleValue
} else {
String.numberFormatter.decimalSeparator = ","
if let result = String.numberFormatter.number(from: self) {
return result.doubleValue
}
}
return 0
}
}
"2.25".doubleValue // 2.25
"2,25".doubleValue // 2.25
Localized approach using NumberFormatter:
extension NumberFormatter {
static let shared = NumberFormatter()
}
extension StringProtocol {
var doubleValue: Double? {
return NumberFormatter.shared.number(from: String(self))?.doubleValue
}
}
Playground testing
// User device's default settings for current locale (en_US)
NumberFormatter.shared.locale // en_US (current)
NumberFormatter.shared.numberStyle // none
NumberFormatter.shared.decimalSeparator // "."
"2.7".doubleValue // 2.7
"2,7".doubleValue // nil
"$2.70".doubleValue // nil
NumberFormatter.shared.numberStyle = .currency
"2.7".doubleValue // nil
"2,7".doubleValue // nil
"$2.70".doubleValue // 2.7
NumberFormatter.shared.locale = Locale(identifier: "pt_BR") // pt_BR (fixed)
"2.7".doubleValue // nil
"2,7".doubleValue // nil
"R$2,70".doubleValue // 2.7
NumberFormatter.shared.numberStyle = .none
"2.7".doubleValue // nil
"2,7".doubleValue // 2.7
"R$2,70".doubleValue // nil
Potential duplicate of the SO Answer, use NSNumberFormatter
Example Swift:
let number = NSNumberFormatter().numberFromString(numberString)
if let number = number {
let floatValue = Float(number)
}
Example (Objective-C):
NSNumber *number = [[NSNumberFormatter new] numberFromString: numberString];
float floatValue = number.floatValue;
Nobody has really addressed the issue directly.
That is, the decimal separator is a convention for a locale.
iOS supports formatting numbers based on a particular locale.
If you're working purely in a given locale, then everything should work correctly. The keypad should accept numbers with the correct decimal separator.
If you're in most countries in Europe, for example, you'd enter a comma as the decimal separator. Entering a dot in those countries is wrong. Somebody from one of those countries would not do that, because it is the wrong decimal separator. A European user is going to know to use a comma as the decimal separator and you don't have to do anything.
If you are in the US, you'd use a period. Using a comma in the US would be wrong.
The way you should display a decimal number is with a number formatter. When you create a number formatter, it uses the current locale by default.
If you need to convert a string containing a decimal number from one locale to the other, you should use 2 number formatters. Use a formatter in the source locale to convert the string to a float. Then use a formatter with the destination locale to convert the number to a string in the output format.
Simply create one number formatter in the default current locale, and create a second number formatter and set it's locale explicitly to the other locale that you want to use.
It's probably a duplicate of this answer, but since the original is in Objective-C, here's a Swift version:
let label = "23,07"
let formatter = NSNumberFormatter()
let maybeNumber = formatter.numberFromString(label)
if let number = maybeNumber {
println(number) // 23.07
}
Swift 3: float or double value for string containing floating point with comma
extension String {
var floatValue: Float {
let nf = NumberFormatter()
nf.decimalSeparator = "."
if let result = nf.number(from: self) {
return result.floatValue
} else {
nf.decimalSeparator = ","
if let result = nf.number(from: self) {
return result.floatValue
}
}
return 0
}
var doubleValue:Double {
let nf = NumberFormatter()
nf.decimalSeparator = "."
if let result = nf.number(from: self) {
return result.doubleValue
} else {
nf.decimalSeparator = ","
if let result = nf.number(from: self) {
return result.doubleValue
}
}
return 0
}
}
Example:
"5,456".floatValue //5.456
"5.456".floatValue //5.456
"5,456".doubleValue //5.456
"5.456".doubleValue //5.456
"5,456".doubleValue.rounded() //5
"5,6".doubleValue.rounded() //6
Since NSNumberFormatter was replaced by NumberFormatter in the recent version of Swift, I would have pleasure to share with you an upgraded possible solution:
var numberFormatter: NumberFormatter()
importo = Float(numberFormatter.number(from: importoPrevistoTF.text!)!)
A solution that i've found:
let nf = NumberFormatter()
nf.locale = Locale.current
let numberLocalized = nf.number(from: txtAlcool.text!)
In my case I was testing on xcode and all goes ok, but when testing on device it was crashing. All because in Brazil we use metric system, comma separated decimal ",". With this solution it converts automatically from comma to dot.
Code working with the current version of Swift:
let amount = "8,35"
var counter: Int = 0
var noCommaNumber: String!
for var carattere in (amount) {
if carattere == "," { carattere = "." }
if counter != 0 { noCommaNumber = "\(noCommaNumber ?? "\(carattere)")" + "\(carattere)" } else { noCommaNumber = "\(carattere)" } // otherwise first record will always be nil
counter += 1
}
let importo = Float(noCommaNumber)
Swift 4 solution, without using preferredLanguages I had issues with fr_US and decimalPad
extension String {
func number(style: NumberFormatter.Style = .decimal) -> NSNumber? {
return [[Locale.current], Locale.preferredLanguages.map { Locale(identifier: $0) }]
.flatMap { $0 }
.map { locale -> NSNumber? in
let formatter = NumberFormatter()
formatter.numberStyle = style
formatter.locale = locale
return formatter.number(from: self)
}.filter { $0 != nil }
.map { $0! }
.first
}
}
textfield.text?.number()?.floatValue
You can convert it by using NumberFormatter and filtering the different decimal separators:
func getDoubleFromLocalNumber(input: String) -> Double {
var value = 0.0
let numberFormatter = NumberFormatter()
let decimalFiltered = input.replacingOccurrences(of: "٫|,", with: ".", options: .regularExpression)
numberFormatter.locale = Locale(identifier: "EN")
if let amountValue = numberFormatter.number(from: decimalFiltered) {
value = amountValue.doubleValue
}
return value
}
let number = NSNumberFormatter()
let locale = NSLocale.currentLocale()
let decimalCode = locale.objectForKey(NSLocaleDecimalSeparator) as! NSString
number.decimalSeparator = decimalCode as String
let result = number.numberFromString(textField.text!)
let value = NSNumberFormatter.localizedStringFromNumber(result!.floatValue, numberStyle: .DecimalStyle)
print(value)
Hope, this helps you :)

how to ignore a value of a UITextField that has already been calculated in swift 3?

I'm trying to make an app that is very basic. One part of the app is that there are 4 textFields and a button that calculates the sum of these textFields.
The problem that I'm facing is that say I type the value 10 in the first textField then I press the button. The result would be 10. However, if I press it again ( without typing anything in the other textFields), the result would be 20!! Furthermore, if I type 20 in one of the other textFields, the result would be 40!!
The result SHOULD BE 30 NOT 40!!
one possible option I thought of (haven't tried it yet) is assigning 0 to all of the textFields when pressing the button. But I'd like the app to be smarter and keep tracks of the result.
if it helps, here's the code inside the button that calculates the sum:
#IBAction func calBtnPressed(_ sender: UIButton) {
var benifit:[Double] = []
var textFields: [Double] = []
if initialBalance.text?.isEmpty ?? true {
// do nothing
} else {
if let temp = initialBalance.text {
// these lines of code will convert arabic numbers to English ones in case the user uses Arabic number
let initialStr: String = temp
let initialFormatter: NumberFormatter = NumberFormatter()
initialFormatter.locale = NSLocale(localeIdentifier: "EN") as Locale!
let initialFinal = initialFormatter.number(from: initialStr)
benifit.append(Double(initialFinal!))
}
}
if income.text?.isEmpty ?? true {
// do nothing
} else {
if let temp = income.text {
// these lines of code will convert Arabic numbers to English ones in case the user uses Arabic number
let incomeStr: String = temp
let incomeFormatter: NumberFormatter = NumberFormatter()
incomeFormatter.locale = NSLocale(localeIdentifier: "EN") as Locale!
let incomeFinal = incomeFormatter.number(from: incomeStr)
benifit.append(Double(incomeFinal!))
}
}
if salaries.text?.isEmpty ?? true {
// do nothing
} else {
if let temp = salaries.text {
let salariesStr: String = temp
let salariesFormatter: NumberFormatter = NumberFormatter()
salariesFormatter.locale = NSLocale(localeIdentifier: "EN") as Locale!
let salariesFinal = salariesFormatter.number(from: salariesStr)
textFields.append(Double(salariesFinal!))
}
}
if tools.text?.isEmpty ?? true {
// do nothing
} else {
if let temp = tools.text {
let toolsStr: String = temp
let toolsFormatter: NumberFormatter = NumberFormatter()
toolsFormatter.locale = NSLocale(localeIdentifier: "EN") as Locale!
let toolsFinal = toolsFormatter.number(from: toolsStr)
textFields.append(Double(toolsFinal!))
}
}
if maintinance.text?.isEmpty ?? true {
// do nothing
} else {
if let temp = maintinance.text {
let maintinanceStr: String = temp
let maintinanceFormatter: NumberFormatter = NumberFormatter()
maintinanceFormatter.locale = NSLocale(localeIdentifier: "EN") as Locale!
let maintinanceFinal = maintinanceFormatter.number(from: maintinanceStr)
textFields.append(Double(maintinanceFinal!))
}
}
if other.text?.isEmpty ?? true {
// do nothing
} else {
if let temp = other.text {
let otherStr: String = temp
let otherFormatter: NumberFormatter = NumberFormatter()
otherFormatter.locale = NSLocale(localeIdentifier: "EN") as Locale!
let otherFinal = otherFormatter.number(from: otherStr)
textFields.append(Double(otherFinal!))
}
}
for textField in textFields {
sumExpenses += textField
}
for ben in benifit{
sumBenifit += ben
}
totalExpenses.text = String(sumExpenses)
totalAfterSubtractingExpenses.text = String( sumBenifit - sumExpenses )
sumBenifit -= sumExpenses
}
I think I found your problem.
You use a variable sumBenefit which isn't declared in your func, so I assume it is declared in your UIViewController.
Since it is an instance variable, it will not reset each time you click the button.
If you want to reset the values of sumExpenses and sumBenefits each time the button is pressed, then you'll have to do something like this:
sumExpenses = 0
for textField in textFields {
sumExpenses = Int(textField.text)!
}
sumBenefit = 0
for ben in benefit {
sumBenefit += ben
}
I am also making the assumption that you want a number from your textField in the first for-loop, because if sumExpenses is of type Int (or any other number for that matter) then sumExpenses += textField will not compile. You need to take the text of that textField and convert it to an Int.
Again, I am still not super clear what you are trying to do, but please let me know if this works for you, or if you need further clarification.

Swift 3: Replacing a "," with a "." in Double [duplicate]

I'm using a textField which is filled from a numerical pad.
Trouble is that, with lot of local region formats (all european, for example), UITextField's numerical pad has comma instead dot, so everytime I write a decimal number, UITextField can't recognise the decimal comma and it round number; for example 23,07 become 23.
How can I solve this?
I thought to set the textField fixed on USA; is it possible? How?
I read the value using this:
var importo = (importoPrevistoTF.text as NSString).floatValue
Swift 4
extension String {
static let numberFormatter = NumberFormatter()
var doubleValue: Double {
String.numberFormatter.decimalSeparator = "."
if let result = String.numberFormatter.number(from: self) {
return result.doubleValue
} else {
String.numberFormatter.decimalSeparator = ","
if let result = String.numberFormatter.number(from: self) {
return result.doubleValue
}
}
return 0
}
}
"2.25".doubleValue // 2.25
"2,25".doubleValue // 2.25
Localized approach using NumberFormatter:
extension NumberFormatter {
static let shared = NumberFormatter()
}
extension StringProtocol {
var doubleValue: Double? {
return NumberFormatter.shared.number(from: String(self))?.doubleValue
}
}
Playground testing
// User device's default settings for current locale (en_US)
NumberFormatter.shared.locale // en_US (current)
NumberFormatter.shared.numberStyle // none
NumberFormatter.shared.decimalSeparator // "."
"2.7".doubleValue // 2.7
"2,7".doubleValue // nil
"$2.70".doubleValue // nil
NumberFormatter.shared.numberStyle = .currency
"2.7".doubleValue // nil
"2,7".doubleValue // nil
"$2.70".doubleValue // 2.7
NumberFormatter.shared.locale = Locale(identifier: "pt_BR") // pt_BR (fixed)
"2.7".doubleValue // nil
"2,7".doubleValue // nil
"R$2,70".doubleValue // 2.7
NumberFormatter.shared.numberStyle = .none
"2.7".doubleValue // nil
"2,7".doubleValue // 2.7
"R$2,70".doubleValue // nil
Potential duplicate of the SO Answer, use NSNumberFormatter
Example Swift:
let number = NSNumberFormatter().numberFromString(numberString)
if let number = number {
let floatValue = Float(number)
}
Example (Objective-C):
NSNumber *number = [[NSNumberFormatter new] numberFromString: numberString];
float floatValue = number.floatValue;
Nobody has really addressed the issue directly.
That is, the decimal separator is a convention for a locale.
iOS supports formatting numbers based on a particular locale.
If you're working purely in a given locale, then everything should work correctly. The keypad should accept numbers with the correct decimal separator.
If you're in most countries in Europe, for example, you'd enter a comma as the decimal separator. Entering a dot in those countries is wrong. Somebody from one of those countries would not do that, because it is the wrong decimal separator. A European user is going to know to use a comma as the decimal separator and you don't have to do anything.
If you are in the US, you'd use a period. Using a comma in the US would be wrong.
The way you should display a decimal number is with a number formatter. When you create a number formatter, it uses the current locale by default.
If you need to convert a string containing a decimal number from one locale to the other, you should use 2 number formatters. Use a formatter in the source locale to convert the string to a float. Then use a formatter with the destination locale to convert the number to a string in the output format.
Simply create one number formatter in the default current locale, and create a second number formatter and set it's locale explicitly to the other locale that you want to use.
It's probably a duplicate of this answer, but since the original is in Objective-C, here's a Swift version:
let label = "23,07"
let formatter = NSNumberFormatter()
let maybeNumber = formatter.numberFromString(label)
if let number = maybeNumber {
println(number) // 23.07
}
Swift 3: float or double value for string containing floating point with comma
extension String {
var floatValue: Float {
let nf = NumberFormatter()
nf.decimalSeparator = "."
if let result = nf.number(from: self) {
return result.floatValue
} else {
nf.decimalSeparator = ","
if let result = nf.number(from: self) {
return result.floatValue
}
}
return 0
}
var doubleValue:Double {
let nf = NumberFormatter()
nf.decimalSeparator = "."
if let result = nf.number(from: self) {
return result.doubleValue
} else {
nf.decimalSeparator = ","
if let result = nf.number(from: self) {
return result.doubleValue
}
}
return 0
}
}
Example:
"5,456".floatValue //5.456
"5.456".floatValue //5.456
"5,456".doubleValue //5.456
"5.456".doubleValue //5.456
"5,456".doubleValue.rounded() //5
"5,6".doubleValue.rounded() //6
Since NSNumberFormatter was replaced by NumberFormatter in the recent version of Swift, I would have pleasure to share with you an upgraded possible solution:
var numberFormatter: NumberFormatter()
importo = Float(numberFormatter.number(from: importoPrevistoTF.text!)!)
A solution that i've found:
let nf = NumberFormatter()
nf.locale = Locale.current
let numberLocalized = nf.number(from: txtAlcool.text!)
In my case I was testing on xcode and all goes ok, but when testing on device it was crashing. All because in Brazil we use metric system, comma separated decimal ",". With this solution it converts automatically from comma to dot.
Code working with the current version of Swift:
let amount = "8,35"
var counter: Int = 0
var noCommaNumber: String!
for var carattere in (amount) {
if carattere == "," { carattere = "." }
if counter != 0 { noCommaNumber = "\(noCommaNumber ?? "\(carattere)")" + "\(carattere)" } else { noCommaNumber = "\(carattere)" } // otherwise first record will always be nil
counter += 1
}
let importo = Float(noCommaNumber)
Swift 4 solution, without using preferredLanguages I had issues with fr_US and decimalPad
extension String {
func number(style: NumberFormatter.Style = .decimal) -> NSNumber? {
return [[Locale.current], Locale.preferredLanguages.map { Locale(identifier: $0) }]
.flatMap { $0 }
.map { locale -> NSNumber? in
let formatter = NumberFormatter()
formatter.numberStyle = style
formatter.locale = locale
return formatter.number(from: self)
}.filter { $0 != nil }
.map { $0! }
.first
}
}
textfield.text?.number()?.floatValue
You can convert it by using NumberFormatter and filtering the different decimal separators:
func getDoubleFromLocalNumber(input: String) -> Double {
var value = 0.0
let numberFormatter = NumberFormatter()
let decimalFiltered = input.replacingOccurrences(of: "٫|,", with: ".", options: .regularExpression)
numberFormatter.locale = Locale(identifier: "EN")
if let amountValue = numberFormatter.number(from: decimalFiltered) {
value = amountValue.doubleValue
}
return value
}
let number = NSNumberFormatter()
let locale = NSLocale.currentLocale()
let decimalCode = locale.objectForKey(NSLocaleDecimalSeparator) as! NSString
number.decimalSeparator = decimalCode as String
let result = number.numberFromString(textField.text!)
let value = NSNumberFormatter.localizedStringFromNumber(result!.floatValue, numberStyle: .DecimalStyle)
print(value)
Hope, this helps you :)

Decimal number in text field

I'm trying to get a decimal number from a text field. It only can be a decimal number but if I enter something like 'o,5', than the bullets will spawn a lot faster than every 0.5 second.
My code:
#IBAction func enemyBulletDelayClick(_ sender: AnyObject) {
dismissKeyboard()
let correctNumber = enemyBulletDelayText.text?.replacingOccurrences(of: ",", with: ".")
enemyBulletDelay = Double(correctNumber!)!
enemyBulletDelayText.text = ""
}
(I'm converting each ',' to a '.' for the decimal numbers.)
Otherwise it would give me an error.
I tried to use this code and it worked!
Code:
let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
enemySpawnDelay = (formatter.number(from: enemySpawnDelayText.text!)?.doubleValue)!
If you have a ? you need to unwrap, not put !
There are a bunch of ways to remove . afterwards. Pick whatever you want. This is more focused on the process of what you're doing and then you can decide on using NSNumberFormatter or whatever you want to do.
guard let enemyBulletDelayString = enemyBulletDelayText.text? else {
//put whatever you want to do here if this check doesn't pass
return
}
let numberFormatter = NumberFormatter()
formatter.numberStyle = numberFormatter.Style.decimal
if let formattedNumber = numberFormatter.number(from: enemyBulletDelayString) {
enemySpawnDelay = formattedNumber.doubleValue
} else {
numberFormatter.decimalSeparator = ","
if let formattedNumber = numberFormatter.number(from: enemyBulletDelayString) {
enemySpawnDelay = formattedNumber.doubleValue
}
}
This should work with what you want to do.

Resources