Thursday, 16 April 2009

NSNumberformatter: some examples

I was looking for some examples on the usage of the NSNumberformatter class. During this search I stumbled on the weblog of Sam Lam which provides some good examples.

I copy them here , as I use my own blog as a sort of FAQ or HOW-TO for myself.

-(NSString*) formatCurrencyValue:(double)value
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setCurrencySymbol:@"$"];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *c = [NSNumber numberWithFloat:value];
return [numberFormatter stringFromNumber:c];
}

-(NSString*) formatPercentValue:(double)value
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setPercentSymbol:@"%"];
[numberFormatter setNumberStyle: NSNumberFormatterPercentStyle];
[numberFormatter setDecimalSeparator:@"."];
[numberFormatter setGeneratesDecimalNumbers:TRUE];
[numberFormatter setMinimumFractionDigits:2];
[numberFormatter setRoundingMode: NSNumberFormatterRoundUp];
[numberFormatter setRoundingIncrement:[[NSNumber alloc]initWithDouble:0.05]];
NSNumber *c = [NSNumber numberWithFloat:value];
return [numberFormatter stringFromNumber:c];
}

-(double) formatDoubleFromCurrency:(NSString*)value
{
double ret ;
if(value)
{
ret = [value doubleValue];
if (ret == 0)
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setCurrencySymbol:@"$"];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *c = [numberFormatter numberFromString:value];
ret = [c doubleValue];
}
return ret;
}
else
return 0.0;
}

No comments:

Post a Comment

Post a Comment