0

I need to change a textfield.text from one number to another but retain the regional use of comma or period for decimal eliminator.

A

NSNumberFormatter* nf = [[NSNumberFormatter alloc] init]; nf.locale = [NSLocale currentLocale]; NSNumber *n = [nf numberFromString:textfield.text]; //converts comma to period if needed

float number = [n floatValue];

float newnumber= number * factor;

B

Now I need to reload into the textfield.text the new number as string and convert period to comma if called for by the region. In other words reverse engineer the first step.

NSNumber *n = [NSNumber numberWithFloat: number]; //say number is 17.22000

textfield.text =[nf stringFromNumber: n];

Doesn't work as truncates to the period "17" Is there a reverse of "A" ??

Ancient
  • 73
  • 4
  • http://stackoverflow.com/questions/11787759/how-to-properly-format-currency-on-ios here you go – amar Nov 08 '13 at 04:41
  • @amar, it would be better if you add it as answer instead of a comment :D – yoninja Nov 08 '13 at 08:40
  • @amar, thanks this works: for B [nf setNumberStyle: NSNumberFormatterDecimalStyle]; NSNumber *n = [NSNumber numberWithFloat:number]; textfield.text= [nf stringFromNumber:n]; – Ancient Nov 09 '13 at 13:16

1 Answers1

1

Use the localizedStringWithFormat method:

NSNumber *yourNumber = [nf numberFromString:yourString];
//to create the formatted NSNumber object

NSString *yourString = [NSString localizedStringWithFormat:@"%.2F", yourNumber];
//to create the localized output

This will show the separator based on the current locale.

JFS
  • 2,992
  • 3
  • 37
  • 48