amateurCoder
amateurCoder

Reputation: 1

Extracting numeric value from UItextfield post-NSFormatter decimal conversion

I am having the user enter into a textfield a number, say 900000. It is then formatted for decimal and shows on the screen as 900,000. When I try to extract the numeric value from the formatted textfield, the number returned is 900. Suggestions?

Upvotes: 0

Views: 41

Answers (2)

zaph
zaph

Reputation: 112855

You could prior to converting to a number delete the , with

stringByReplacingOccurrencesOfString:@"," withString:@""

But this will not work in much of the world where a ' is used as the decimal point.

Better to use an NSNumberFormatter:

NSNumberFormatter *numberFormatter = [NSNumberFormatter new];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *numberObject = [numberFormatter numberFromString:@"900,000"];
NSLog(@"numberObject: %@", numberObject);
int numberInt = [numberObject intValue];
NSLog(@"numberInt: %d", numberInt);

Output:

numberObject: 900000
numberInt: 900000

Upvotes: 1

chiliNUT
chiliNUT

Reputation: 19573

have you tried removing the comma?

str = [str stringByReplacingOccurrencesOfString:@","
                                     withString:@""];

int value = [str intValue];

Upvotes: 0

Related Questions