如何使用千位分隔符和2个小数点将float转换为NSString?

时间:2018-04-03 08:46:40

标签: ios objective-c nsnumber nsnumberformatter

我想将floatvalue转换为带有千位分隔符和2位小数的NSString,但没有运气。随附我的代码: - 任何错误?

NSString *str = [NSString stringWithFormat:@"%.2f", [_goodPrice floatValue]];
NSLog(@"166 - %@",str); //Result = 900000.00

NSNumber *myNumber = @((int)([_goodPrice floatValue]*100)/100.0);
NSLog(@"169 - %@",myNumber); //Result = 900000

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:[_goodPrice floatValue]]];
NSLog(@"Result...%@",numberString);//Result = 900,000. HOW CAN I MAKE IT 900,000.00   ???

2 个答案:

答案 0 :(得分:3)

请根据您的要求使用NSNumberFormatterCurrencyStyle

NSString *str = [NSString stringWithFormat:@"%.2f", [_goodPrice floatValue]];
NSLog(@"166 - %@",str);

NSNumber *myNumber = @((int)([_goodPrice floatValue]*100)/100.0);
NSLog(@"169 - %@",myNumber);

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setCurrencySymbol:@""];
NSNumber *num = [NSNumber numberWithDouble:[str doubleValue]];
NSLog(@"Result...%@",[numberFormatter stringFromNumber:num]);

答案 1 :(得分:2)

NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormatter setCurrencySymbol:@""]; //To remove currency symbol
NSLog(@"%@", [currencyFormatter stringFromNumber:[NSNumber numberWithDouble:[_goodPrice floatValue]]]);