0

我正在尝试将这样的 123456.567 数字设为美元的 123,456.56 和任何其他货币的 123,456.567

我的代码是:

double fromAgainstJOD = amountVal * fromCurrency.SellRate;
double result = fromAgainstJOD / toCurrency.SellRate;

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setGroupingSeparator:@","];
[formatter setGroupingSize:3];
[formatter setUsesGroupingSeparator:YES];

NSString* formattedString = [formatter stringFromNumber:[NSNumber numberWithDouble:result]];

if (toCurrency.SellRate == 0) {
    result = 0;
}
if ([toCurrency.Code isEqualToString:@"USD"]) {
    [resultLbl setText:[NSString stringWithFormat:@"%@ %0.2f", toCurrency.Code, result]];     
} else {
    [resultLbl setText:[NSString stringWithFormat:@"%@ %0.3f", toCurrency.Code, result]]; 
}

所以我想在 resultLbl 中为每个货币代码设置带有千位分隔符和小数部分的数字。美元 => 2 分数其他货币 => 3 分数

4

2 回答 2

1

这是修复。在您检查美元的格式化程序中,如果 USD 将 formatWidth 设置为 2,否则设置为 3

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setGroupingSeparator:@","];
[formatter setGroupingSize:3];
[formatter setUsesGroupingSeparator:YES];

NSString* formattedString;

if (toCurrency.SellRate == 0) {
    result = 0;
}
if ([toCurrency.Code isEqualToString:@"USD"]) {
    [formatter setFormatWidth:2];
    formattedString = [formatter stringFromNumber:[NSNumber numberWithDouble:result]];
    [resultLbl setText:[NSString stringWithFormat:@"%@ %0.2f", toCurrency.Code, result]];     
}else
{
    [formatter setFormatWidth:3];
    formattedString = [formatter stringFromNumber:[NSNumber numberWithDouble:result]];
    [resultLbl setText:[NSString stringWithFormat:@"%@ %0.3f", toCurrency.Code, result]]; 

}

看起来 setFormat 出现在 ios 文档中,即使它不起作用。

样本来自:

NSNumberFormatter *numberFormatter =[[NSNumberFormatter alloc] init];
NSMutableDictionary *newAttrs = [NSMutableDictionary dictionary];

[numberFormatter setFormat:@"$#,##0.00;($#,##0.00)"];
[newAttrs setObject:[NSColor redColor] forKey:@"NSColor"];
[numberFormatter setTextAttributesForNegativeValues:newAttrs];
[[textField cell] setFormatter:numberFormatter];

https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html

于 2013-01-07T15:25:28.497 回答
0

我知道该怎么做

if ([toCurrency.Code isEqualToString:@"USD"]) {
    [formatter setFormatWidth:2];
    formatter.maximumFractionDigits = 3;
    formatter.minimumFractionDigits = 3;
    formattedString = [formatter stringFromNumber:[NSNumber numberWithDouble:result]];

    [resultLbl setText:formattedString];
}else
{
    [formatter setFormatWidth:3];
    formatter.maximumFractionDigits = 2;
    formatter.minimumFractionDigits = 2;
    formattedString = [formatter stringFromNumber:[NSNumber numberWithDouble:result]];
    [resultLbl setText:formattedString];
}
于 2013-01-14T07:22:45.937 回答