20

我有一个NSNumberFormatter我试图用它来从一个NSNumber. 无论我尝试哪种咒语,我都会得到两位小数。我的代码是:

NSNumberFormatter *fmtCurrency = [[[NSNumberFormatter alloc] init] autorelease];
[fmtCurrency setNumberStyle: NSNumberFormatterCurrencyStyle];
[fmtCurrency setGeneratesDecimalNumbers:FALSE];
[fmtCurrency setCurrencyCode:@"GBP"];
[fmtCurrency setCurrencySymbol:@"£"];
txtTotal.text = [fmtCurrency stringFromNumber: result.Bill ]; // this is an NSNumber
4

6 回答 6

44

我想你想用零调用 setMaximumFractionDigits 。

NSNumberFormatter *fmtCurrency = [[[NSNumberFormatter alloc] init] autorelease];
[fmtCurrency setNumberStyle: NSNumberFormatterCurrencyStyle];
[fmtCurrency setGeneratesDecimalNumbers:NO];
[fmtCurrency setCurrencyCode:@"GBP"];
[fmtCurrency setCurrencySymbol:@"£"];

NSNumber* myNumber = [NSNumber numberWithFloat:12.34];
NSString* myString = [fmtCurrency stringFromNumber:myNumber];
NSLog( @"the number is %@", myString );

[fmtCurrency setMaximumFractionDigits:0];
myString = [fmtCurrency stringFromNumber:myNumber];
NSLog( @"now it's %@", myString );  


2011-07-25 01:05:39.823 FormatterTest[841:707] the number is £12.34
2011-07-25 01:05:39.824 FormatterTest[841:707] now it's £12
于 2011-07-25T08:07:42.043 回答
13

您可以尝试以下方法

[fmtCurrency setGeneratesDecimalNumbers:NO];
[fmtCurrency setMaximumFractionDigits:0];

或者

intValueNSNumber@Praveen 的建议中获取

于 2011-07-25T08:30:55.650 回答
4

您需要从NSNumber中提取intValue

于 2011-07-25T07:56:26.497 回答
1

斯威夫特 4

    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 0
于 2019-08-29T12:03:43.507 回答
0

您可以删除所有 NSNumberFormatter (这非常密集),然后执行以下操作:

txtTotal.text = [NSString stringWithFormat:@"£%d", result.Bill.intValue];
于 2011-07-25T12:49:27.250 回答
-2

将字符串格式化为小数点后两位...(是我正在搜索的内容)改编...

            float distance = //distance with many decimals...;

            NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
            [numberFormatter setMaximumFractionDigits:2];

            //new distance with two decimals
            NSNumber* myNumber = [NSNumber numberWithFloat:distance];

祝你好运

于 2012-01-12T11:40:08.733 回答