1

我想用 stringWithFormat 从一个双精度值创建一个字符串,最后没有不必要的零。

例子:

  1. [NSString stringWithFormat:@"%.8f",2.344383933];

  2. [NSString stringWithFormat:@"%.8f",2.0];

预期成绩:

  1. 2.344383933

  2. 2

哪种格式正确?

谢谢你。

4

2 回答 2

0

有一个专门的数字格式类,NSNumberFormatter

let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 8

print("\(formatter.stringFromNumber(2.344383933))")
print("\(formatter.stringFromNumber(2.0))")

NSNumberFormatter还会带来本地化(小数点、分组分隔符)。

于 2016-03-18T22:49:35.920 回答
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

于 2015-07-27T23:42:08.250 回答