如果需要,正确使用格式说明符以显示最多三位小数,否则显示零位小数?
我发现 %g 在需要时仅显示小数。如果数字是整数,则不会添加尾随 0.000,这样就很好。 但在例如 1.12345 的情况下,我希望它将答案缩短为 1.123。 在 1.000 的情况下,我只想显示 1,就像 %g 已经做的那样。
我尝试在字符串中指定 %.3g,但这不起作用。 如果有人有答案,我将不胜感激!
I've found %g to show only decimals if needed. If the number is whole, no trailing .000 is added, so thats good.
But in the case of for example 1.12345 I want it to short the answer to 1.123.
And in the case of 1.000 I want to only show 1, as %g already does.
I've tried to specify %.3g in the string, but that doesn't work.
If anyone has the answer, I'd be grateful!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我通过 IEEE 规范 回顾了“格式字符串”的功能据我了解,您希望的行为是不可能的。
我建议您使用 NSNumberFormatter 类。我写了一个符合您希望的行为的示例。我希望这有帮助:
I reviewed the abilities of a "format string" via the IEEE Specification and as I understand it your wished behavior is not possible.
I recommend to you, to use the NSNumberFormatter class. I wrote an example that matches your wished behavior. I hope that helps:
NSLog(@"%.3g", 1.12345) 会得到什么?
我做了一些测试,据我了解你的问题,你走在正确的轨道上。这些是我的结果:
要得到你想要的,请使用@“%.4g”。
What do you get for NSLog(@"%.3g", 1.12345)?
I did some tests and as I understand your question you're on the right track. These are my results:
To get what you want use @"%.4g".
以下是 Jan 针对 Swift 4 的解决方案:
Here is Jan's solution for Swift 4: