gpt4 book ai didi

ios - 设置数字格式以显示千位和小数分隔符

转载 作者:行者123 更新时间:2023-11-29 04:12:34 24 4
gpt4 key购买 nike

我正在尝试将 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 分数

最佳答案

这是修复方法。在你检查美元或其他的格式化程序中,如果美元将 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

关于ios - 设置数字格式以显示千位和小数分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14198696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com