Question

I got an NSInteger that looks like "8444". I would like to display it in the following way "84.44". If the integer looks like "84455" then it should look like "844.55". If it is "85544433" then it should look like "855.444.33".

Any suggestion? I wanted to use NSStringWithFormat but I do not know which tags to provide.

Was it helpful?

Solution

You can modify the representation of a number depending on the locale, in fact, it would be better if you would allow iOS to detect the proper locale and apply the corresponding format, it can vary a lot from one to other country according to http://en.wikipedia.org/wiki/Decimal_mark.

In your example you are using a NSInteger but I am guessing that the 2 last numbers are the decimal part, if so, you could do it this way and keep locale consistency:

NSInteger integer = 8444;
// Convert integet to decimal
NSNumber *number = [NSNumber numberWithFloat:((float)integer/100)];
// Create formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
// Conver number to string
NSString *str = [formatter stringFromNumber:number];

That code will use the locale configured on iOS, but if you want to force one specifically, you can do it by adding these lines before the conversion:

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale:locale];

OTHER TIPS

Got it:

- (NSString *)formattedStringFromInteger:(NSInteger)number {
    NSString *result = @"0";
    if (number != 0) {
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
        numberFormatter.groupingSeparator = @".";
        NSString *string = [numberFormatter stringFromNumber:@(number * 10)];
        result = [string substringToIndex:string.length - 1];
    }
    return result;
}

8444 -> 84.44
101 -> 1.01
10100000 -> 101.000.00
0 -> 0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top