格式化数字以显示千位和小数分隔符

时间:2013-01-07 15:17:21

标签: ios objective-c formatting

我试图将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中为每个货币代码设置千位分隔符和小数分数。 USD => 2分数 其他货币=> 3分数

2 个答案:

答案 0 :(得分:1)

这是修复。如果USD将formatWidth设置为2,则在格式化程序中检查usd或其他格式,否则设置为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

答案 1 :(得分: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];
}