I want to format my UILabel with commas or better with a dollar sign and commas (with no decimal).
Here is the code I am using:
IBOutlet UILabel *labelrev
float rev = (x + y)
labelrev.text = [[NSString alloc] initWithFormat:@%2.f",rev];
I get xxxxxxxxx as the output I want to get xxx,xxx,xxx or $xxx,xxx,xxx
How do I do that?
The standard comma style format contains up to two decimal points and a thousand separators and locks the dollar sign to the extreme left half of the cell. Negative numbers are shown in enclosures.
To apply a format to a cell or range of cells first select the cell(s) and then from the Home tab do one of the following. Use the Accounting, Percentage, Comma, Increase and Decrease Decimal places buttons to quickly apply formatting to the data. Click the Accounting drop-down to apply different currency symbols.
First, select the cells or range of cells or the entire column where to apply the comma style. After that, go to the “Home” tab and click on the comma (,) icon under the “Number” group on the ribbon. Once you click on the comma (,) icon, your selected range will get applied with comma separators in the number values.
Select the cells that you want to format and then, in the Number group on the Home tab, click the down arrow in the Number Format box. Choose either Currency or Accounting.
You should definitely use NSNumberFormatter
for this. The basic steps are:
This code sets up the number formatter. I've done everything that you want except the currency bit. You can look that up in the documentation.
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *groupingSeparator = [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator];
[formatter setGroupingSeparator:groupingSeparator];
[formatter setGroupingSize:3];
[formatter setAlwaysShowsDecimalSeparator:NO];
[formatter setUsesGroupingSeparator:YES];
Next, you want to set up your number and return a formatted string. In your case, we wrap a double in an NSNumber. I do it inline, but you can break it up into two steps:
NSString *formattedString = [formatter stringFromNumber:[NSNumber numberWithFloat:rev];
Don't forget to clean up!
[formatter release];
A quick note about localization:
The NSLocale class provides some useful info about the user's locale. In the first step, notice how I used NSLocale to get a localized grouping separator:
NSString *groupingSeparator = [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator];
(Some countries use a full-stop/period, while others use a comma.) I think there's a way to get a localized currency symbol as well, but I'm not one hundred percent sure, so check the documentation. (It depends upon what your trying to do.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With