Convert basic script to Objective C (money formatting)

前端 未结 2 865
日久生厌
日久生厌 2021-01-16 12:00

I\'ve got this basic like script that I need to convert to objective c, it turns big units of money into shortened versions (ie: 1.2m, etc), I\'ve got most of the conversion

2条回答
  •  旧巷少年郎
    2021-01-16 12:34

    .... Okay, with thanks to the author of the Cocoa Tidbits blog, I believe I have a solution which is much more elegant, faster and doesn't require so much coding; it still needs testing, and it also probably requires a little more editing, but it seems to be much better than my original.

    I modified the script a little to make it not show any trailing zeros where relevant;

        NSNumberFormatter *nformat = [[NSNumberFormatter alloc] init];
        [nformat setFormatterBehavior:NSNumberFormatterBehavior10_4];
        [nformat setCurrencySymbol:@"$"];
        [nformat setNumberStyle:NSNumberFormatterCurrencyStyle];
        double doubleValue = 10200;
        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]] ];
                NSUInteger stringLen = [stringValue length];
    
                if ( [stringValue hasSuffix:@".00"] )
                {               
                    // Remove suffix
                    stringValue = [stringValue substringWithRange: NSMakeRange(0, stringLen-3)];            
                } else if ( [stringValue hasSuffix:@".0"] ) {
    
                    // Remove suffix
                    stringValue = [stringValue substringWithRange: NSMakeRange(0, stringLen-2)];
    
                } else if ( [stringValue hasSuffix:@"0"] ) {
    
                    // Remove suffix
                    stringValue = [stringValue substringWithRange: NSMakeRange(0, stringLen-1)];        
                }
    
    
                // Add the letter suffix at the end of it
                stringValue = [stringValue stringByAppendingString: s];
    
                //stringValue = [NSString stringWithFormat: @"%@%@", [nformat stringFromNumber: [NSNumber numberWithDouble: doubleValue]]  , s] ;
                break ;
            }   
        } 
    
        NSLog(@"Cash = %@", stringValue);
    

提交回复
热议问题