-
Notifications
You must be signed in to change notification settings - Fork 1
/
DSShortNumberFormatter.m
81 lines (66 loc) · 3.04 KB
/
DSShortNumberFormatter.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#import "DSShortNumberFormatter.h"
@implementation DSShortNumberFormatter
- (instancetype)init {
self = [super init];
if (self) {
NSURL *pattern_plist_url = [NSBundle.mainBundle URLForResource:@"patterns" withExtension:@"plist"];
pattern_dict = [[NSDictionary alloc] initWithContentsOfURL:pattern_plist_url];
}
return self;
}
- (void)dealloc {
[pattern_dict release];
[super dealloc];
}
- (NSArray<NSDictionary<NSString *, NSString *> *> *)patternsForLocale:(NSLocale *)locale {
NSString *identifier = locale.localeIdentifier;
if (pattern_dict[identifier])
return pattern_dict[identifier];
NSArray<NSString *> *components = [identifier componentsSeparatedByString:@"_"];
if (components.firstObject && pattern_dict[components.firstObject])
return pattern_dict[components.firstObject];
return pattern_dict[@"root"];
}
- (NSString *)stringFromNumber:(NSNumber *)number {
if (self.numberStyle == NSNumberFormatterPercentStyle ||
self.numberStyle == NSNumberFormatterScientificStyle)
return [super stringFromNumber:number];
double num_val = number.doubleValue;
NSArray<NSDictionary<NSString *, NSString *> *> *patterns = [self patternsForLocale:self.locale];
NSString *orig_positive_format = self.positiveFormat;
NSString *orig_negative_format = self.negativeFormat;
for (NSDictionary<NSString *, NSString *> *patternInfo in patterns) {
NSString *pattern = patternInfo[@"pattern"];
NSString *count = patternInfo[@"count"];
NSString *type = patternInfo[@"type"];
/* I don't think non-other patterns are different
* for the short patterns. If this ever supports
* the long pattern it will be necessary to
* distinguish "one", "two", "few", and "many"
*/
if (![count isEqualToString:@"other"])
continue;
if (fabs(num_val) >= [type doubleValue]) {
NSInteger type_zeroes = type.length - 1;
NSInteger pattern_zeroes = 0;
NSInteger first_zero = -1;
for (int i=0; i<pattern.length; i++) {
if ([pattern characterAtIndex:i] == '0') {
if (first_zero == -1)
first_zero = i;
pattern_zeroes++;
}
}
self.multiplier = @(__exp10(-(type_zeroes - pattern_zeroes + 1)));
self.positiveFormat = [pattern stringByReplacingCharactersInRange:NSMakeRange(first_zero, pattern_zeroes)
withString:orig_positive_format];
self.negativeFormat = [pattern stringByReplacingCharactersInRange:NSMakeRange(first_zero, pattern_zeroes)
withString:orig_negative_format];
}
}
NSString *result = [super stringFromNumber:number];
self.positiveFormat = orig_positive_format;
self.negativeFormat = orig_negative_format;
return result;
}
@end