NSNumberFormatter的乘数向下舍入而不是显示分数

时间:2012-01-23 11:33:01

标签: iphone ios nsnumberformatter

我已经配置了一个NSNumberFormatter来将在NSDictionary中存储为美分的金额转换为欧元。因为它们存储为美分,所以我将格式化程序的multiplier设置为[NSNumber numberWithDouble:0.01]。然而,当我试图以欧元显示304欧分时,我得到€ 3,00

这让我相信乘数是整数除法而不是双除法。

NSFormatter配置

/** 
 Returns an NSNumberFormatter that can be used to display currency in euro's (as determined in The Netherlands).
 */
+ (NSNumberFormatter *)euroCurrencyFormatter 
{
    static NSNumberFormatter *numberFormatter = nil;
    @synchronized(self) {
        if (!numberFormatter) {
            numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
            [numberFormatter setMultiplier:[NSNumber numberWithDouble:0.01]];
            NSLocale *nlLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"nl_NL"];
            [numberFormatter setLocale:nlLocale];
            [nlLocale release];
        }
    }
    return numberFormatter;
}

调用NSFormatter

cell.detailTextLabel.text = [[NSNumberFormatter euroCurrencyFormatter] stringFromNumber:[breakdown valueForKey:@"VatAmount"]]; // The VAT amount would be 304.

结果

€ 3,00

如何阻止错误的行为?

2 个答案:

答案 0 :(得分:3)

试试这段代码。

cell.detailTextLabel.text = [[NSNumberFormatter euroCurrencyFormatter] stringFromNumber:[NSNumber numberWithDouble:[[breakdown valueForKey:@"VatAmount"] doubleValue]]]; // The VAT amount would be 304.

如果您将VAT作为整数传递,您将获得始终采用int格式的数字。

答案 1 :(得分:0)

请参阅NSNumberFormatter reference的“配置舍入行为”。