使用NSNumberFormatter防止小数

时间:2011-07-25 07:49:19

标签: iphone ios string-formatting nsnumberformatter

我有一个NSNumberFormatter,我试图用来从NSNumber生成一定数量的GBP(£)。无论我尝试哪种咒语,我都会得到两位小数。我的代码是:

    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

6 个答案:

答案 0 :(得分:40)

我想你想用零调用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

答案 1 :(得分:9)

您可以尝试以下

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

根据@Praveen

的建议,从intValue获取NSNumber

答案 2 :(得分:3)

您需要从intValue中提取NSNumber

答案 3 :(得分:0)

您可以删除所有NSNumberFormatter(这是非常密集的),只需执行:

txtTotal.text = [NSString stringWithFormat:@"£%d", result.Bill.intValue];

答案 4 :(得分:0)

雨燕4

    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 0

答案 5 :(得分:-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];
祝你好运