Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert english numbers inside a string to Persian/Arabic numbers in Objective-C?

I have an english string that may or may not have numbers. But i want those numbers to be printed on screen as Persian numbers.

For example if NSString *foo = @"a string with numbers 1 2 3;"

then output should be a string with numbers ۱۲۳

The code I'm using right now is :

-(NSString *)convertEnNumberToFarsi:(NSString *) number{
    NSString *text;
    NSDecimalNumber *someNumber = [NSDecimalNumber decimalNumberWithString:number];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fa"];
   [formatter setLocale:gbLocale];
   text = [formatter stringFromNumber:someNumber];
   return text;
}

This method only converts a string that is only in numbers, but as mentioned above i want to convert any string that may or may not have numbers in it.

How can i achieve this?

like image 490
Sobhan Avatar asked May 27 '15 10:05

Sobhan


2 Answers

The simple way:

NSDictionary *numbersDictionary = @{@"1" : @"۱", @"2" : @"۲", @"3" : @"۳", @"4" : @"۴", @"5" : @"۵", @"6" : @"۶", @"7" : @"۷", @"8" : @"۸", @"9" : @"۹",@"0" : @"٠"};
for (NSString *key in numbersDictionary) {
  str = [str stringByReplacingOccurrencesOfString:key withString:numbersDictionary[key]];
}

Other solution more flexible with locale:

NSNumberFormatter *formatter = [NSNumberFormatter new];
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"ar"];
for (NSInteger i = 0; i < 10; i++) {
  NSNumber *num = @(i);
  str = [str stringByReplacingOccurrencesOfString:num.stringValue withString:[formatter stringFromNumber:num]];
}

Note: this code wrote without IDE, it can be with syntax errors.

like image 81
Gralex Avatar answered Sep 20 '22 03:09

Gralex


In swift 3:

func convertEngNumToPersianNum(num: String)->String{
    let number = NSNumber(value: Int(num)!)
    let format = NumberFormatter()
    format.locale = Locale(identifier: "fa_IR")
    let faNumber = format.string(from: number)

    return faNumber!
}

Check before force unwrap to prevent crash.

like image 36
Vahid Avatar answered Sep 20 '22 03:09

Vahid