Frage

I am making a calculator application now. Somehow, I could do show the number to display as NSString. But, I want to do add comma in the number in display. I searched the method to add ,(comma) in the number, but I am not sure how to use the method. I would like to convert DisplayNumber(without comma) to DisplayNumber(with comma) through createStringAddedCommaFromInt method. How should I solve ???

*DisplayNumber, firstNumber, secondNumber are int.

-(void)show{
        DisplayNumber = firstNumber + secondNumber;
        labelTotal.text = [NSString stringWithFormat:@"%g", DisplayNumber];
}

- (NSString *)createStringAddedCommaFromInt:(NSInteger)number
{
NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setGroupingSeparator:@","];
[format setGroupingSize:3];

return [format stringForObjectValue:[NSNumber numberWithInt:number]];
}
War es hilfreich?

Lösung

In addition to setting the grouping separator, you need to tell NSNumberFormatter to use it:

NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
format.locale = [NSLocale currentLocale]; // <<== Don't forget to set the locale
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setGroupingSeparator:@","];
[format setGroupingSize:3];
format.usesGroupingSeparator = YES; // <<== Add this line

This should produce the number with comma separators.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top