【问题标题】:Correct use of format specifier to show up to three decimals if needed, otherwise zero decimals?如果需要,正确使用格式说明符以显示最多三位小数,否则为零小数?
【发布时间】:2011-09-01 14:10:06
【问题描述】:

如果需要,我发现 %g 只显示小数。如果数字是整数,则不添加尾随 .000,这很好。 但在例如 1.12345 的情况下,我希望它缩短到 1.123 的答案。 在 1.000 的情况下,我只想显示 1,因为 %g 已经这样做了。

我尝试在字符串中指定 %.3g,但这不起作用。 如果有人有答案,我将不胜感激!

【问题讨论】:

    标签: objective-c ios nsstring stringwithformat format-specifiers


    【解决方案1】:

    我通过IEEE Specification 查看了“格式字符串”的功能,据我了解,您希望的行为是不可能的。

    我向你推荐,使用 NSNumberFormatter 类。我写了一个与您希望的行为相匹配的示例。希望对您有所帮助:

    NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [numberFormatter setMaximumFractionDigits:2];
    [numberFormatter setDecimalSeparator:@"."];
    [numberFormatter setGroupingSeparator:@""];
    NSString *example1 = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:123456.1234]];
    NSLog(@"%@", example1);
    NSString *example2 = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:123456.00]];
    NSLog(@"%@", example2);
    

    【讨论】:

    • Jan Weinkauff - 非常感谢!令人惊讶的是,周围还有像你一样的人,愿意利用自己的时间为他人寻找答案!
    【解决方案2】:

    NSLog(@"%.3g", 1.12345) 得到了什么?

    我做了一些测试,据我了解,您的问题是正确的。这些是我的结果:

    NSLog(@"%g", 1.000000);    => 1
    NSLog(@"%g", 1.123456789);  => 1.12346
    NSLog(@"%.1g", 1.123456789);  => 1
    NSLog(@"%.2g", 1.123456789);  => 1.1
    NSLog(@"%.3g", 1.123456789);  => 1.12
    NSLog(@"%.4g", 1.123456789);  => 1.123
    

    要得到你想要的,请使用@"%.4g"。

    【讨论】:

    • 感谢您的回复,但仍然无法正常工作。
    • %.3g 不会显示半大数字,如 100 000。打印为 1E+05,这并不理想:D %.3f 似乎最适合,但总是留下尾随零当一个整数.. :(
    • 如何将 123456.1234 打印为 123456.12,以及将 123456.00 打印为 123456?两位小数,仅在需要时使用..?
    【解决方案3】:

    这是 Jan 针对 Swift 4 的解决方案:

    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .decimal
    numberFormatter.maximumFractionDigits = 2
    numberFormatter.decimalSeparator = "."
    numberFormatter.groupingSeparator = ""
    let example1 = numberFormatter.string(from: 123456.1234)!
    print(example1)
    let example2 = numberFormatter.string(from: 123456.00)!
    print(example2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多