Search code examples
objective-cnumbersnumberformatter

How to modify number using NSNumberFormatter?


I have values such as:

5.1M (5100000)
80M (80000000)
300.5M (300500000)

5K (5000)
2000K (2000000)
200.5K (200500)

(Values I need to turn them into are in parenthesis behind the numbers).

Basically, a number can have a decimal point or no decimal point, can end with K (for thousand) or M (for million), but ONLY when it's a whole number (i.e. 0.5M needs to be 500000; no commas).

I also need to be able to convert numbers back to their original form.

How do I do this, and what's the best way to do it?


Solution

  • So you're saying you have an NSString that starts with a number and ends with K or M? And you want to see what it consists of, and convert it to an actual numeric value? This is a job for NSScanner.

    Though, to be quite honest, NSScanner was around long before regular expressions became available in Objective-C; nowadays I might just use NSRegularExpression.

    Or, if you know for a fact that it really is a number followed by K or M, then you don't even have to do that. Just pull the last character off the end. That's the K or the M and you now know which it is. And what's left is a numeric string and you can just convert it to a number.

    Pseudocode (not tested):

    NSString* s = @"5.1M";
    NSUInteger len = s.length;
    NSString* numPart = [s substringToIndex: len-2];
    NSString* unitPart = [s substringFromIndex: len-1];
    int multiplier = 1000;
    if ([unitPart isEqualToString: @"M"])
        multiplier = 1000000;
    float result = numPart.floatValue * multiplier;