I could convert English numbers to Arabic numbers in Xcode. but now I want to convert Arabic/Persian numbers to English numbers in iOS ...
Please guide me about this...
This is my code for conversion (English to Arabic) :
- (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;
}
I have a simpler solution with String Extension: extension String{ /// To convert Arabic / Persian numbers to English /// - Returns: returns english number func changeToEnglish()-> String{ let numberFormatter = NumberFormatter() numberFormatter. locale = Locale(identifier: "EN") let engNumber = numberFormatter.
Thus, reading numbers in Arabic is no different from English. This should give you one less thing to worry about when managing your Arabic source text.
Try this, I hope this helps you :
NSString *NumberString = @"۸۸۸";
NSNumberFormatter *Formatter = [[NSNumberFormatter alloc] init];
NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"EN"];
[Formatter setLocale:locale];
NSNumber *newNum = [Formatter numberFromString:NumberString];
if (newNum) {
NSLog(@"%@", newNum);
}
//print in console 888
You must take care of not only Persian numbers, but also Arabic ones.
Use the below functions/methods to do so:
// Convert string From English numbers to Persian numbers
+(NSString *) convertToPersianNumber:(NSString *) string {
NSNumberFormatter *formatter = [NSNumberFormatter new];
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"fa"];
for (NSInteger i = 0; i < 10; i++) {
NSNumber *num = @(i);
string = [string stringByReplacingOccurrencesOfString:num.stringValue withString:[formatter stringFromNumber:num]];
}
return string;
}
// Convert string From Arabic/Persian numbers to English numbers
+(NSString *) convertToEnglishNumber:(NSString *) string {
NSNumberFormatter *formatter = [NSNumberFormatter new];
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"fa"];
for (NSInteger i = 0; i < 10; i++) {
NSNumber *num = @(i);
string = [string stringByReplacingOccurrencesOfString:[formatter stringFromNumber:num] withString:num.stringValue];
}
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"ar"];
for (NSInteger i = 0; i < 10; i++) {
NSNumber *num = @(i);
string = [string stringByReplacingOccurrencesOfString:[formatter stringFromNumber:num] withString:num.stringValue];
}
return string;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With