I have a UITextField
: its text is a longitude (double) value. My device prints this double with a dot, eg 24.000000
(and not 24,00000
).
That said, the textfield should not accept invalid values: to do that, I use the decimalPad
keyboard, that contains numbers and a decimal sign (in my case, the sign is ,
, NOT .
but it looks like this varies based on locales).
When the user edits the textfield, the double value is passed to a MapKit
map, so that value must be valid before I pass it.
The validity of a latitude value is quite clear (value>-90
and value<90
), but I don't know how to convert the string to a valid double.
First of all, in my case, the initial data come from:
mapView.convert(touchPoint, toCoordinateFrom: mapView)
This one returns coordinates with a dot and displays that coordinate in the textfield.
Second: if the user is editing the textfield, he can delete a dot but he can't insert it anymore. Its dot should be replaced by a comma because in the decimal pad I only have a comma.
Third: I tried this extension:
extension String {
struct NumFormatter {
static let instance = NumberFormatter()
}
var doubleValue: Double? {
return NumFormatter.instance.number(from: self)?.doubleValue
}
}
to test if the value in the textfield is a double or not. If I insert a comma, it considers the value a double. If I insert a dot, the value is nil.
How do I validate my longitude value?