Question

I have app with three view controllers. First is UIViewController with three UITextField's where user put some digits. These digits are stored to my CoreData entity as String attributes.

Second is UITableView, where I show my stored data from CoreData as new cell. Third is detail UIViewController where I show user all his previously inserted digits. The problem is when I set on textField decimal pad, user have digits and comma but my function need digits with dot for double precision calculating. With comma I can't make mathematical function as [.....] * [...] = .... because it doesn't work.

Any idea how I can figure it out? Can I simply change that comma to a dot?

I have this code:

 NSNumberFormatter*nf = [[NSNumberFormatter alloc]init];
[nf setNumberStyle:NSNumberFormatterDecimalStyle];

double result = [myString doubleValue] * [myOtherString doubleValue];
Was it helpful?

Solution

You want the decimal keypad to have either a comma or a period (dot) based on the user's locale. This is so the user can enter the value as they are accustomed to. In order for you to do the math with the vales, you need to use a NSNumberFormatter to convert the entered string into a double value. Once you do this, your math formulas will work. Never use doubleValue or floatValue to convert an NSString to a double or float if the string was entered by the user. Always use NSNumberFormatter to properly deal with the user's locale.

Update based on code added to question.

You don't use the number formatter. You are doing exactly what I said not to do. Change your code to:

double firstValue = [[nf numberFromString:myString] doubleValue];
double secondValue = [[nf numberFromString:myOtherString] doubleValue];
double result = firstValue * secondValue;

OTHER TIPS

Solution is very simple:

  1. Go to Settings > General > International > Regional Format
  2. Now select "United States"

Now run your App and see dot(.) instead of comma(,) in Decimal pad keyboard.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top