Problems with String to Double

Hello

I'm very new to Swift and unfortunately I can't get any further with a problem.

I have the problem that the error below occurs when reading a text field that can only contain numbers.

I use the decimal pad with German localization on the keyboard for "myTextField". This means that a comma is entered instead of a period. That's probably where the error is. How can I solve the problem that does not occur with integers.

Thanks for the support.

@IBOutlet weak var  myTextField: UITextField!
var myVariable : Double = 0.0

myVariable = Double(myTextField.text!)!

Error message: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Works after a long search:

myVariable = (myTextField.text! as NSString).doubleValue

This means that a comma is entered instead of a period.

If you’re trying to convert a localised string to a number, you should look to NumberFormatter.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

2 Likes

It took a while because my English isn't the best either.
With the help of apple and some manuals I got around to it and hope to have found the right way:

let newVariable = NumberFormatter()
               newVariable.numberStyle = .decimal
               newVariable.locale = Locale(identifier: "de_DE")
                newVariable.number(from: myTextField.text!)

            if let x = newVariable.number(from: myTextField.text!) {
                myVariable = x.doubleValue
            }

Should it be Foundation's new FormatStyle, FloatingPointFormatStyle instead of NumberFormatter?

Sure, if you can figure out how to use format styles (-: But keep in mind that Jörg wants to parse, not format, and that calls for FloatingPointParseStrategy:

let en = Locale(identifier: "en_AU")
let enFS = FloatingPointFormatStyle<Double>(locale: en)
let enPS = FloatingPointParseStrategy(format: enFS, lenient: true)
let enD = try enPS.parse("3.141")
print(enD)  // 3.141

let de = Locale(identifier: "de_DE")
let deFS = FloatingPointFormatStyle<Double>(locale: de)
let dePS = FloatingPointParseStrategy(format: deFS, lenient: true)
let deD = try dePS.parse("2,718")
print(deD)  // 2.718

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

1 Like

Are you saying there is some problem parsing using the new FormatStyle and ParseableFormatStyle?

To parse a double, I do:

try Double(input, format: .number)
1 Like

Are you saying there is some problem parsing using the new
FormatStyle and ParseableFormatStyle?

Nope. It was just snark about the inscrutability of format styles in general O-:

To parse a double, I do

Yep. The goal of my example was pull apart the pieces to show how they fit together and to demo customisation.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

1 Like