| Index | Submit class | Submit snippet | Submission feed | List |

BSByteFormatter

Language: Objective-C, Author: Michele Balistreri
License: Public domain

This is a formatter (NSFormatter subclass) which converts NSNumber instances representing mostly sizes in bytes and converts them to a human readable string (2048 => "2 KB"). It supports unit of measure up to the Terabyte. Note that input is assumed to be an NSNumber and no checks are performed about it.

BSByteFormatter source preview

#import "BSByteFormatter.h"

@implementation BSByteFormatter

- (NSString *)stringForObjectValue:(id)anObject
{
  NSArray *sizeTable = [NSArray arrayWithObjects:@"B", @"KB", @"MB", @"GB", @"TB", nil];
    
  int i;
  float result = [anObject floatValue];
  
  if([anObject respondsToSelector:@selector(length)])
  {
    return anObject;
  }
  
  for(i = 0; i < 5 && result >= 1024; i++)
  {
    result = result/1024;
  }
  
  if((float)(result - (int)result) > 0.01)
  {
    return [NSString localizedStringWithFormat:@"%.2f %@", result, [sizeTable objectAtIndex:i]];
  }
  
  else
  {
    return [NSString localizedStringWithFormat:@"%.0f %@", result, [sizeTable objectAtIndex:i]];  
  }
}

@end

BSByteFormatter header preview

#import <Cocoa/Cocoa.h>

@interface BSByteFormatter : NSFormatter
{

}

@end
Download Archive

Compatible with:


Comments

Chris Ryland says:

Perhaps too nit-picky, my DRY "code smell sense" suggests you replace that last if with something like the following, "hoisting out" the small difference in those two returns:

NSString *format;

if ((float) (result - (int) result) > 0.01)
format = @"%.2f %@";
else
format = @"%.0f %@";
return [NSString localizedStringWithFormat:format, result, [sizeTable objectAtIndex:i]];

Name

Website

Do you hate spammers? (Answer "Yes")