1
self.numberFormatter = [[NSNumberFormatter alloc] init];
[self.numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[self.numberFormatter setCurrencySymbol:@""];
[self.numberFormatter setLocale:[NSLocale currentLocale]];
//In DataManager sharedClass .h 
- (void)setupCapital:(float)Capital;
- (float)readCapital;
(NSString*)formatCapital:(NSNumber *)Capital;

// In DataManager sharedClass .m
@property (assign, nonatomic) float theCapital;
- (NSString *) formatCapital:(NSNumber *)Capital {
return [self.numberFormatter stringFromNumber:Capital];
}

- (void)formatCapital:(float)Capital {
self.theCapital = Capital;
}

- (float) readCapital {
return self.theCapital;
}

// write the number
 float numberDecimal = [[DataManager sharedClass] readCapital];
self.labelCapital.text = [[DataManager sharedClass] formatCapital:[NSNumber numberWithFloat:numberDecimal]];

为什么如果我插入 123456,89 我在 labelCapital 中正确地有值 123.456,89

如果我插入 1234567,89 我有 labelCapital 1.234.567,88

如果我插入 123456789,89 我在 labelCapital 123.456.792,00

有什么提示吗?

4

2 回答 2

6

我已经使用该代码解决了:

self.numberFormatter = [[NSNumberFormatter alloc] init];
[self.numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[self.numberFormatter setGroupingSize:3];
[self.numberFormatter setCurrencySymbol:@""];
[self.numberFormatter setLocale:[NSLocale currentLocale]];
[self.numberFormatter setMaximumFractionDigits:2];

并将 float 更改为 double

我还添加了最后一行以得到只有 2 个十进制数字的结果

于 2012-11-06T06:41:42.263 回答
2

您可以使用这样的单个函数将字符串变量转换为货币格式:

  - (NSString *)convertToCommaSeparated:(NSString *)inputAmount{
    NSDecimalNumber *someAmount = [NSDecimalNumber decimalNumberWithString:inputAmount];
    NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    [currencyFormatter setCurrencyCode:@"USD"];
    [currencyFormatter setMaximumFractionDigits:2];
    [currencyFormatter setFormat:@"#,##0.00"];
    return [currencyFormatter stringFromNumber:someAmount];
}

注意:输入不应包含逗号 (,)。在传递给此函数之前,您应该删除逗号。

于 2012-11-05T07:44:51.030 回答