how to convert arabic number to english number - objective-c

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;
}

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;
}

Follow the same. Just replace your locale identifier with "en".

Related

ios7 NSNumberFormatter decimal style unexpected output

NSNumberFormatter is returning garbage data. The variable of interest is milesString at the bottom. It is rounding to 2 instead of 1.6388. I threw in the debugger info and also added the debugging code for testString and num2. For reference, DistanceFormatter is static, not modified anywhere but this function. I've tried replacing it with a local instance to see if the static object was causing the problem (it wasn't). Another note, I got this error when I wasn't using a roudingMode.
-(NSString *)distanceStringFromLocation:(CLLocation *)location {
if (!DistanceFormatter) {
DistanceFormatter = [NSNumberFormatter alloc];
[DistanceFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
DistanceFormatter.roundingMode = NSNumberFormatterRoundCeiling;
DistanceFormatter.minimumFractionDigits = 0;
DistanceFormatter.maximumFractionDigits = 4;
}
CLLocationDistance distance = [_location distanceFromLocation:location];
distance = distance / 1000;
NSLocale *locale = [NSLocale currentLocale];
BOOL isMetric = [[locale objectForKey:NSLocaleUsesMetricSystem] boolValue];
if (isMetric) {
return [NSString stringWithFormat:#"%# kilometers away", [DistanceFormatter stringFromNumber:[NSNumber numberWithFloat:distance]]];
} else {
CGFloat miles = 0.621371 * distance; //miles = (CGFloat) 1.63877738
NSNumber *num = [NSNumber numberWithFloat:miles]; //num = (__NSCFNumber *)(float)1.63878
NSString *testString = [NSString stringWithFormat:#"%f", miles]; //testString = (__NSCFString *) #"1.63877"
NSNumber *num2 = [DistanceFormatter numberFromString:testString]; //num2 = (NSNumber *)nil
NSString *milesString = [DistanceFormatter stringFromNumber:num]; //milesString = (__NSCFString *)#"2"
return [NSString stringWithFormat:#"%# miles away", milesString];
}
}
You have allocated, but not initialized the date formatter.
DistanceFormatter = [NSNumberFormatter alloc];
should be
DistanceFormatter = [[NSNumberFormatter alloc] init];
With that change you get the result milesString = #"1.6388" .

NSNumberFormatter unable to allow numbers to start with a 0

So I'm attempting to automatically add slashes between 2 digits when a user enters in their birthday, but for some reason when the birthday starts with a 0, the number formatter erases it and messes up the birthday. I've got my code below, could someone help me figure out how to do this? Thanks in advance!
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init] ;
[formatter setGroupingSeparator:#"/"];
[formatter setGroupingSize:2];
[formatter setUsesGroupingSeparator:YES];
[formatter setSecondaryGroupingSize:2];
NSString *num = textField.text ;
if(![num isEqualToString:#""])
{
num= [num stringByReplacingOccurrencesOfString:#"/" withString:#""];
NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
textField.text=str;
}
What you could do is the following:
Check the length of the string
If length mod 2 == 0 then add "/"
Log your string
I'm not saying this is recommended but it might help you a bit!
- (void)controlTextDidChange:(NSNotification *)obj{
NSString *num = [textField stringValue] ;
if (num.length%2==0)
{
NSString *someText = [NSString stringWithFormat: #"%#/ ", num];
num = someText;
}
textField.stringValue = num;
}
Something like this may help:
NSMutableString *string = #"YOUR TEXTFIELD TEXT";
NSString *lastString = [string substringWithRange:NSMakeRange(string.length-2, 1)];
if ([lastString isEqualToString:#"/"]) {
return;
}
if (string.length == 2 || string.length == 5) {
[string appendString:#"/"];
}

NSNumberFormatter currency remove trailing zeros

I want to format prices like 45.50 but I don't want prices like 45.00. How can I avoid this?
I did it this way:
NSNumber *amount = #(50.5);
NSNumberFormatter *currencyFormat = [[NSNumberFormatter alloc] init];
[currencyFormat setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormat setLocale:[NSLocale currentLocale]];
if (trunc(amount.floatValue) == amount.floatValue) {
[currencyFormat setMaximumFractionDigits:0];
} else {
[currencyFormat setMaximumFractionDigits:2];
}
NSLog(#"%#", [currencyFormat stringFromNumber:amount]);
I like this solution for its simplicity. Output will be $50.50. And for amount = #(50.0) will be $50
Do this:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:22.368511]];
NSLog(#"Result...%#",numberString);//Result 22.37
Now trail unwanted like this:
NSString* CWDoubleToStringWithMax2Decimals(double d) {
NSString* s = [NSString stringWithFormat:#"%.2f", d];
NSCharacterSet* cs = [NSCharacterSet characterSetWithCharacterInString:#"0."];
NSRange r = [s rangeOfCharacterInSet:cs
options:NSBackwardsSearch | NSAnchoredSearch];
if (r.location != NSNotFound) {
s = [s substringToIndex:r.location];
}
return s;
}
If you're just after a very quick and dirty hack . . .
// Get the price as a string
NSString *priceString = [NSString stringWithFormat:#"%2.2f", priceFloat];
// Trim if needed
if ([priceString hasSuffix:#".00"])
priceString = [priceString substringToIndex:priceString.length-3];
NB This method won't work for localised content i.e. In Europe the decimal separator is a comma so you will see 45,00, not 45.00.
float myOriginalPrice = 45.50;
CGFloat mod = fmod(myOriginalPrice, 1);
if (mod == 0){
mod = (int)myOriginalPrice;
NSLog(#"%.0f", mod);
} else {
NSLog(#"%f", myOriginalPrice);
}
INPUT : 12.74 OR 12.745
NSString *inputString=[NSString string];
inputString=[NSString stringWithFormat:#"%.4g",12.74f];
NSLog(#"inputString : %# \n\n",inputString);
OUTPUT:
inputString : 12.74
INPUT : 12.00 OR 12.000
NSString *inputString=[NSString string];
inputString=[NSString stringWithFormat:#"%.4g",12.00f];
NSLog(#"inputString : %# \n\n",inputString);
OUTPUT:
inputString : 12
UPDATED ANSWER: for his comment question
INPUT:12.30
i assume here he is going to show this value in some UI like UILabel,.....Not For Calculation.
NSString *inputString=[NSString string];
inputString=[NSString stringWithFormat:#"%.4g",12.30f];
NSArray *arr=[inputString componentsSeparatedByString:#"."];
if ([arr count] >= 2) {
NSString *secondStr=[arr objectAtIndex:1];
if ([secondStr length]<2) {
inputString=[NSString stringWithFormat:#"%#0",inputString];
}
}
NSLog(#"inputString : %# \n\n",inputString);
OUTPUT:
inputString : 12.30

How can i display the number in such a format?

I am displaying a number in textfield. Which displays the number as "1234" but i want to display it as in format of "1,234" if i enter another large number which displays as "12345" but i want to display it as "12,345" if i enter 123456 which has to display as "123,456" . How do I format this number in desired format?
-(void)clickDigit:(id)sender
{
NSString * str = (NSString *)[sender currentTitle];
NSLog(#"%#",currentVal);
if([str isEqualToString:#"."]&& !([currentVal rangeOfString:#"."].location == NSNotFound) )
{
return;
}
if ([display.text isEqualToString:#"0"])
{
currentVal = str;
[display setText:currentVal];
}
else if([currentVal isEqualToString:#"0"])
{
currentVal=str;
[display setText:currentVal];
}
else
{
if ([display.text length] <= MAXLENGTH)
{
currentVal = [currentVal stringByAppendingString:str];
NSLog(#"%#",currentVal);
[display setText:currentVal];
}
currentVal=display.text;
}
}
This is the code i am using to display the number in textfield.
EDIT: I Changed my code into the following but still don't get the number correctly formatted:
if ([display.text length] <= MAXLENGTH) {
currentVal = [currentVal stringByAppendingString:str];
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *tempNum = [myNumFormatter numberFromString:currentVal];
NSLog(#"My number is %#",tempNum);
[display setText:[tempNum stringValue]];
currentVal=display.text;
}
You can do it like this:
int myInt = 12345;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *number = [NSNumber numberWithInt:myInt];
NSLog(#"%#", [formatter stringFromNumber:number]); // 12,345
Edit
You didn't implement this correctly, the key is to obtain the string representation of the number using [formatter stringFromNumber:number], but you didn't do that. So change your code into:
currentVal = [currentVal stringByAppendingString:str];
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *tempNum = [myNumFormatter numberFromString:currentVal];
NSLog(#"My number is %#",tempNum);
[display setText:[myNumFormatter stringFromNumber:tempNum]]; // Change this line
currentVal=display.text;
NSLog(#"My formatted number is %#", currentVal);
First, read through the list of methods on the NSNumberFormatter reference page. After doing that, you'll probably realize that you need to use the -setHasThousandSeparators: method to turn on the thousand separators feature. You can also use the -setThousandSeparator: method to set a custom separator, though you probably won't need to do that.

How to display date as "15th November 2010" in iPhone SDK?

HI,
I need to display date as "15th November 2010" in iPhone SDK.
How do I do that?
Thanks!
You can use a Date Formatter as explained in this post:
// Given some NSDate* date
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"dd MMM yyyy"];
NSString* formattedDate = [formatter stringFromDate:date];
I believe you can simply just put "th" at the end of the dd in the format string. like this:
#"ddth MMM yyy
but I don't have my Mac in front of me to test it out. If that doesn't work you can try something like this:
[formatter setDateFormat:#"dd"];
NSString* day = [formatter stringFromDate:date];
[formatter setDateFormat:#"MMM yyyy"];
NSString* monthAndYear = [formatter stringFromDate:date];
NSString* date = [NSString stringWithFormat:#"%#th %#", day, monthAndYear];
I know I'm answering something old; but I did the following.
#implementation myClass
+ (NSString *) dayOfTheMonthToday
{
NSDateFormatter *DayFormatter=[[NSDateFormatter alloc] init];
[DayFormatter setDateFormat:#"dd"];
NSString *dayString = [DayFormatter stringFromDate:[NSDate date]];
//yes, I know I could combined these two lines - I just don't like all that nesting
NSString *dayStringwithsuffix = [myClass buildRankString:[NSNumber numberWithInt:[dayString integerValue]]];
NSLog (#"Today is the %# day of the month", dayStringwithsuffix);
}
+ (NSString *)buildRankString:(NSNumber *)rank
{
NSString *suffix = nil;
int rankInt = [rank intValue];
int ones = rankInt % 10;
int tens = floor(rankInt / 10);
tens = tens % 10;
if (tens == 1) {
suffix = #"th";
} else {
switch (ones) {
case 1 : suffix = #"st"; break;
case 2 : suffix = #"nd"; break;
case 3 : suffix = #"rd"; break;
default : suffix = #"th";
}
}
NSString *rankString = [NSString stringWithFormat:#"%#%#", rank, suffix];
return rankString;
}
#end
I grabbed the previous class method from this answer: NSNumberFormatter and 'th' 'st' 'nd' 'rd' (ordinal) number endings