Objective-C format currency


Here’s the sample code to perform currency format in Objective-C
I realize the code is cut up on the right margin. You can’t read some of it but they are there, try copy-and-paste.

-(NSString*) formatCurrencyValue:(double)value
{
  NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init] autorelease;
  [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] autorelease;
  [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] autorelease;
      [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
      [numberFormatter setCurrencySymbol:@"$"];
      [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
      NSNumber *c = [numberFormatter numberFromString:value];
      ret = [c doubleValue];
     }
     return ret;
  }
  else
    return 0.0;
}
About these ads

One thought on “Objective-C format currency

  1. you need to autorelease the numberFormatter variables, otherwise you will have a memory leak

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

    becomes

    NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s