0

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?

moonvader
  • 19,761
  • 18
  • 67
  • 116
  • 2
    It would be better if you used the NSNumberFormatter class. By default it would take the encoding of the settings, so you wouldn't even need to set it up. – Ricard Pérez del Campo Jul 01 '15 at 08:41
  • can you show me how? – moonvader Jul 01 '15 at 08:42
  • Sorry I don't have the time to write an example, just look for how to use the NSNumberFormatter. It's pretty easy. If you can't find it out (I doubt it), I can write an example as an answer later on. Good luck! – Ricard Pérez del Campo Jul 01 '15 at 08:43
  • possible duplicate of [How to convert an NSString into an NSNumber](http://stackoverflow.com/questions/1448804/how-to-convert-an-nsstring-into-an-nsnumber) – Volker Jul 01 '15 at 08:51
  • @Volker there is solution for swift here? And maybe there is something about Decimal Pad settings? – moonvader Jul 01 '15 at 09:05
  • The difference between Swift and Obj-C with NSNumberFormatter is marginal. One should be able to use the code within seconds... – Volker Jul 01 '15 at 09:33

1 Answers1

4

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

Andrea
  • 26,120
  • 10
  • 85
  • 131