Reputation: 21121
I have UITextField with Decimal Pad and i want to convert it's value to float.
var myValue: Float = NSString(string: myTextField.text).floatValue
On my emulator i have no problems: in Decimal Pad i see numbers and "." so i can enter values like 123.45, but on device i have a problem because on decimal pad i see numbers and ",". So after adding "123,45" to myTextField i see that
myValue = 123
I know that i can change "." to "," in setting but i am really not sure about my app users.
So my problem is - how can i get float value from decimal pad not only with "." using Swift?
I see two kind of solutions: 1) how can i config decimal pad to show "." instead of "," on any device? 2) how can i convert to float strings with "," delimiter?
Upvotes: 0
Views: 531
Reputation: 26383
I have this snippet only in ObjC, but the answer is that you need to use an NSNumberFormatter
, the problem is due to a difference in how locale
is managed from the input to the inner float representation.
numberformatter = [[NSNumberFormatter alloc] init];
[numberformatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberformatter setMaximumFractionDigits:2];
[numberformatter setMinimumFractionDigits:0];
[numberformatter setLocale:[NSLocale currentLocale]];
Here more hints on how to use number formatters
Upvotes: 4