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
任何提示?
答案 0 :(得分: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个十进制数
答案 1 :(得分: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];
}
注意:输入不应该有逗号(,)。你应该在传递给这个函数之前删除逗号。