抑制不必要的零

时间:2011-01-30 14:43:41

标签: ios objective-c iphone ipad stringwithformat

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

示例:

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

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

  3. 预期结果:

    1. 2.344383933

    2. 2

    3. 哪种格式正确?

      谢谢。

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也会带来本地化(小数点,分组分组)。