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?
The simple way:
Other solution more flexible with locale:
Note: this code wrote without IDE, it can be with syntax errors.
In swift 3:
Check before force unwrap to prevent crash.
Swift 3:
However other answers are correct, there is a little problem in converting
String
toInt
.Converting a
String
toInt
removes left zeros which is not good (Specially in converting cell phones and national Ids). To avoid this problem I prefer replacing each English number to Persian.This method can also be used to replace numbers within text and its not necessary to have a pure number to convert to Persian.
I'm afraid there is no other way than replacing them.
e.g.: