RadoJakubes RadoJakubes - 3 years ago 310
Swift Question

Converting to Double from String causing crash in Swift

I'm trying to convert a textfield's text, which can be only numbers because of decimal number pad keyboard.

The variable I'm working with:

static var selectedMoneyMissing: Double = 30.0

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.roundingMode = .down

let roundedReplacing = formatter.string(from: NSNumber(value: Double(textField.text!.replacingOccurrences(of: ",", with: "."))!))

let roundedReplacingSecond = roundedReplacing.replacingOccurrences(of: " ", with: "")

FiltersViewController.selectedMoneyMissing = Double(roundedReplacingSecond)!

I'm getting "unexpectedly found nil...." error:


This error occurs only when I'm putting value >= 1000. So I thought it could be because of the whitespace which is the reason why the roundedReplacingSecond variable exists. But it still does not work (actually, I don't know why the console is printing the variable "roundedReplacingSecond" with whitespace?).

Answer Source

You should configure your NumberFormatter more restrictive, especially by forbidding the use of a grouping and thousand separator:

formatter.groupingSeparator = false
formatter.hasThousandSeparator = false

See the documentation for even more properties. Then it shouldn't be necessary to do the text replacements at all, which may break depending on the users locale.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download