How to convert english numbers inside a string to Persian/Arabic numbers in Objective-C?
The simple way:
NSDictionary *numbersDictionary = @{@"1" : @"۱", @"2" : @"۲", @"3" : @"۳", @"4" : @"۴", @"5" : @"۵", @"6" : @"۶", @"7" : @"۷", @"8" : @"۸", @"9" : @"۹"};
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.
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.
Swift 3:
However other answers are correct, there is a little problem in converting String
to Int
.
Converting a String
to Int
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.
static func convertToPersian(text : String)-> String {
let numbersDictionary : Dictionary = ["0" : "۰","1" : "۱", "2" : "۲", "3" : "۳", "4" : "۴", "5" : "۵", "6" : "۶", "7" : "۷", "8" : "۸", "9" : "۹"]
var str : String = text
for (key,value) in numbersDictionary {
str = str.replacingOccurrences(of: key, with: value)
}
return str
}
This method can also be used to replace numbers within text and its not necessary to have a pure number to convert to Persian.