Thursday, July 1, 2010

How to Change String format from "48821869.89" to "48,821,869.89"

-(NSString*)convertStringInCommaFormat:(NSString*) inputStr
{
double strInDouble = [inputStr doubleValue];
int strInInt = strInDouble;
float strFloatingPart = strInDouble - strInInt;
NSString* temp = [NSString stringWithFormat:@"%d",strInInt];
int check = [temp length] % 3;

NSString* strFinal= @"";
if(check != 0)
{
NSString* ch =[temp substringWithRange:NSMakeRange(0, check)];
strFinal = [strFinal stringByAppendingString:[NSString stringWithFormat:@"%@,",ch]];
}
for(int k = 0 ; k<[temp length]/3 ; k++)
{
NSString* ch =[temp substringWithRange:NSMakeRange(check, 3)];
strFinal = [strFinal stringByAppendingString:[NSString stringWithFormat:@"%@,",ch]];
check = check+3;
}

NSString* final = [strFinal substringWithRange:NSMakeRange(0, [strFinal length] - 1)];
NSString* strTemp = [NSString stringWithFormat:@"%0.2f",strFloatingPart];
NSString* strAfterDot = [strTemp substringWithRange:NSMakeRange(1, [strTemp length] - 1)];
final = [final stringByAppendingString:[NSString stringWithFormat:@"%@",strAfterDot]];

return final;
}

No comments:

Post a Comment