Thursday, 5 August 2010

NSNumberformatter for special currency formats

Another day somebody asked me if it was possible with an NSNumberFormatter to format currency values like $1k , $1,02m etc.

So instead of displaying a value like $1,020,000 to display it as $1,02m

Now with a standard NSNumberFormatter its not possible, so you could create a custom formatter for that.

The following code snippet will do the job

- (NSString *) formatCurrencyValue: (double )doubleValue

{

NSNumberFormatter *nformat = [[NSNumberFormatter alloc] init];

[nformat setFormatterBehavior:NSNumberFormatterBehavior10_4];

[nformat setCurrencySymbol:[[NSLocale currentLocale] objectForKey: NSLocaleCurrencySymbol]];

[nformat setNumberStyle:NSNumberFormatterCurrencyStyle];

NSString *stringValue = nil;

NSArray *abbrevations = [NSArray arrayWithObjects:@"k", @"m", @"b", @"t", nil] ;

for (NSString *s in abbrevations)

{

doubleValue /= 1000.0 ;

if ( doubleValue < 1000.0 )

{

if ( (long long)doubleValue % (long long) 100 == 0 )

[nformat setMaximumFractionDigits:0];

else

[nformat setMaximumFractionDigits:2];

stringValue = [NSString stringWithFormat: @"%@%@", [nformat stringFromNumber: [NSNumber numberWithDouble: doubleValue]] , s] ;

break ;

}

}

[nformat release] ;

NSLog(@"Value = %@", stringValue);

return stringValue ;

}


Input :

[self formatCurrencyValue: 1235.0f] ;

[self formatCurrencyValue: 10351.0f] ;

[self formatCurrencyValue: 100522.0f] ;

[self formatCurrencyValue: 1235111.0f] ;

[self formatCurrencyValue: 12351234.0f] ;

[self formatCurrencyValue: 192351234.0f] ;

[self formatCurrencyValue: 1872351234.0f] ;

Output :

Value = £1.24k

Value = £10.35k

Value = £101k

Value = £1.24m

Value = £12.35m

Value = £192.35m

Value = £1.87b


Note : you can add additional parameters to the function like number of fraction digits

No comments:

Post a Comment