我有一个NSString,其编号为0.871,我试图将其转换为如此显示87.1%
我尝试使用NSNumberFormatter来获得该结果,但我不能让它显示3位数。实现这一结果的最佳方法是什么?感谢。
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterPercentStyle];
NSNumber *number = [formatter numberFromString:inputString];
[formatter release];
答案 0 :(得分:4)
NSString * str = @"0.863";
NSString * newStr = [NSString stringWithFormat:@"%.1f%%", [str floatValue]*100];
答案 1 :(得分:2)
如果您尝试将字符串转换为数字,请格式化数字:
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:inputString];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterPercentStyle];
NSString *formattedString = [formatter stringFromNumber:number];
[formatter release];
如果您只想将“0.871”变成数字87.1:
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:inputString];
NSDecimalNumber *percentNumber = [number decimalNumberByMultiplyingByPowerOf10:2];
答案 2 :(得分:1)
只需使用setMinimumFractionDigits:
NSNumber *myNumber = [NSNumber numberWithFloat:0.871];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterPercentStyle];
[formatter setMinimumFractionDigits:1];
NSLog(@"%@", [formatter stringFromNumber:myNumber]); // 87.1%
这也确保了对语言环境适当格式化百分比。