RadoJakubes
RadoJakubes

Reputation: 15

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: "")
print(roundedReplacing)
print(roundedReplacingSecond)

FiltersViewController.selectedMoneyMissing = Double(roundedReplacingSecond)!

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

screenshot

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?).

Upvotes: 0

Views: 742

Answers (1)

mschmidt
mschmidt

Reputation: 2790

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.

Upvotes: 1

Related Questions