Skip to content

Instantly share code, notes, and snippets.

@akhenakh
Last active August 29, 2015 14:18
Show Gist options
  • Save akhenakh/c3e8dee3114c238a0a0f to your computer and use it in GitHub Desktop.
Save akhenakh/c3e8dee3114c238a0a0f to your computer and use it in GitHub Desktop.
Round numbers to Units 102.000 to 102K 9.900 to 9.9K 1.000.200 to 1M
#import "NBUnitsNumberFormatter.h"
@implementation NBUnitsNumberFormatter
- (NSString *)stringForObjectValue:(id)value; {
if (![value isKindOfClass:[NSNumber class]]) {
return nil;
}
return [self stringForFloat:[value floatValue]];
}
- (NSString *)stringForFloat:(float)v {
NSString *unit;
float rounded = v;
float m = 0.0;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
if (v <= 999) {
return [NSString stringWithFormat:@"%.0f", v];
}
else if (v >= 1000 && v < 1000000) {
m = fmod(rounded, 1000);
rounded = rounded / 1000.0;
if (m < 100 || rounded > 99) {
[formatter setMaximumFractionDigits:0];
}
unit = @"K";
}
else if (v >= 1000000) {
m = fmod(rounded, 1000000);
rounded = rounded / 1000000.0;
if (m < 100000 || rounded > 99) {
[formatter setMaximumFractionDigits:0];
}
unit = @"M";
}
[formatter setRoundingMode:NSNumberFormatterRoundFloor];
NSString *val = [formatter stringFromNumber:[NSNumber numberWithFloat:rounded]];
return [NSString stringWithFormat:@"%@%@", val, unit];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment