Search code examples
iosobjective-cnsdecimal

Converting very large NSDecimal to string eg. 400,000,000,000 -> 400 T and so forth


I am making a game that requires me to use very large numbers. I believe I am able to store very large numbers with NSDecimal. However, when displaying the numbers to users I would like to be able to convert the large number to a succinct string that uses characters to signify the value eg. 100,000 -> 100k 1,000,000 -> 1.00M 4,200,000,000 -> 4.20B and so forth going up to extremely large numbers. Is there any built in method for doing so or would I have to use a bunch of

NSDecimalCompare statements to determine the size of the number and convert?

I am hoping to use objective c for the application.

I know that I can use NSString *string = NSDecimalString(&NSDecimal, _usLocale); to convert to a string could I then do some type of comparison on this string to get the result I'm looking for?


Solution

  • Solved my issue: Can only be used if you know that your NSDecimal that you are trying to format will only be a whole number without decimals so make sure you round when doing any math on the NSDecimals.

    -(NSString *)returnFormattedString:(NSDecimal)nsDecimalToFormat{
    
    NSMutableArray *formatArray = [NSMutableArray arrayWithObjects:@"%.2f",@"%.1f",@"%.0f",nil];
    
    NSMutableArray *suffixes = [NSMutableArray arrayWithObjects:@"k",@"M",@"B",@"T",@"Qa",@"Qi",@"Sx",@"Sp",@"Oc",@"No",@"De",@"Ud",@"Dud",@"Tde",@"Qde",@"Qid",@"Sxd",@"Spd",@"Ocd",@"Nvd",@"Vi",@"Uvi",@"Dvi",@"Tvi", nil];
    
    int dick = [suffixes count];
    
    NSLog(@"count %i",dick);
    
    NSString *string = NSDecimalString(&nsDecimalToFormat, _usLocale);
    NSString *formatedString;
    NSUInteger characterCount = [string length];
    if (characterCount > 3) {
    
        NSString *trimmedString=[string substringToIndex:3];
    
        float a;
    
        a = 100.00/(pow(10, (characterCount - 4)%3));
        int remainder = (characterCount-4)%3;
    
    
        int suffixIndex = (characterCount + 3 - 1)/3 - 2;
        NSLog(@"%i",suffixIndex);
        if(suffixIndex < [suffixes count]){
            NSString *formatSpecifier = [formatArray[remainder] stringByAppendingString:suffixes[suffixIndex]];
            formatedString= [NSString stringWithFormat:formatSpecifier,  [trimmedString floatValue] / a];
    
        }
        else {
            formatedString = @"too Big";
        }
    
    }
    else{
        formatedString = string;
    }
    
    return formatedString;
    
    }