English 中文(简体)
Objective-C: How to format string as $ Price
原标题:

Is their a built-in way of formatting string as $ price, e.g. 12345.45 converted to $12,345.45?

最佳回答

Assuming you are using Cocoa (or just Foundation), you can use NSNumberFormatter and set its style to currency:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
... = [formatter stringFromNumber:number];

By default it uses the locale of your system, but you can change that and lots of other properties, see the NSNumberFormatter API docs.

问题回答

Assuming the price is held in a float, you probably want +localizedStringWithFormat:.

NSString *priceString = [NSString localizedStringWithFormat:@"$ % .2f",price];

Hmmm... Apple says they follow the IEEE standard for printf, so it should accept the flag, but it doesn t work on Tiger. NSNumberFormatter it is.

You need to get rid of the character

So, just have this:

NSString *priceString = [NSString localizedStringWithFormat:@"$ %.2f", price];
NSString *formatedNumbers = [NSNumberFormatter localizedStringFromNumber:myNumber numberStyle:NSNumberFormatterCurrencyStyle];




相关问题
How to make all text upper case / capital?

I want all texts in TextBlock, Label, MenuItem.Header to be displayed in upper case. The strings are taken from a ResourceDictionary e.g.: <TextBlock Text="{StaticResource String1}"/> <...

New Line Haskell

Hey。 关于本周的辅导,其中一个问题要求采用其他功能格式Line和格式List编制一个行文清单,从而形成一种功能格式。

Formatting comments in LaTeX s algorithmic environment

I want to typeset an algorithm in LaTeX. I m using the algorithmic package and environment to do so. Everything is working great except when I add comments (using COMMENT), they are output ...

How can I format columns without using Perl s format?

Often in Perl I want to print out column/row data, say, from a hash. This is simple: foreach my $k(keys %h) { print $k, " ", $h{$k}, " "; } However, if the key happens to have ...

NSDateFormat, super simple! Where am I screwing up?

Ok, this is really simple, maybe I m a getting a bit burnt out, but seems like it should work, Query XML feed, put out date string, format, display in a cell. The issue is I m a getting a NULL ...

A "safe" python HTML text formatting (ala textile)

I ve been looking around for an existing python library in the style of textile to format text for users to enter. If it was just me entering it, just textile would have been fine, but since the ...

热门标签