我想从double值创建一个stringWithFormat的字符串,最后没有不必要的零。
示例:
[NSString stringWithFormat:@"%.8f",2.344383933];
[NSString stringWithFormat:@"%.8f",2.0];
预期结果:
2.344383933
2
哪种格式正确?
谢谢。
答案 0 :(得分:0)
使用NSNumberFormatter
[numberFormatter numberFromString:[NSString stringWithFormat:@"%.8f",0]]
样品:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSLog(@"1: %@",[numberFormatter numberFromString:[NSString stringWithFormat:@"%.8f",2.344383933]]);
NSLog(@"2: %@",[numberFormatter numberFromString:[NSString stringWithFormat:@"%.8f",2.0]]);
结果:
1: 2.344383933
2: 2
答案 1 :(得分:0)
有一个专门的数字格式类NSNumberFormatter
:
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 8
print("\(formatter.stringFromNumber(2.344383933))")
print("\(formatter.stringFromNumber(2.0))")
NSNumberFormatter
也会带来本地化(小数点,分组分组)。