在 NSString 中使用舍入双精度数
我遇到的情况是,我有很多不同的 double
值,例如 1.00、0.25 和 2.50
。我想对这些双精度数进行四舍五入,使它们成为 1、0.25 和 2.5;换句话说,我想删除所有尾随的 0。有办法做到这一点吗?
目前我一直在使用 %.2f
,我想知道是否可以利用它但以某种方式对其进行调整。请问有人可以帮我吗?
I have a situation where I have lots of different double
values, for example 1.00, 0.25 and 2.50
. I would like to round these doubles
so that they become 1, 0.25 and 2.5
; in other words I want to remove any trailing 0's. Is there a way to do this?
At the moment I have been using %.2f
, and I'm wondering if I can make use of this but adapt it in some way. Please can someone help me out?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只要您只讨论显示,这就很简单。您想要的 格式说明符 是
%g
:相同的格式说明符可以与 NSNumberFormatter 一起使用,这也可以让您对有效数字进行一些控制。
当然,尾随零不能从数字存储在内存中的方式中删除。
As long as you're talking only about display, this is quite easy. The format specifier you want is
%g
:The same format specifier can be used with an
NSNumberFormatter
, which will also give you some control over significant digits.The trailing zeroes can't be removed from the way the number is stored in memory, of course.
我相信您希望使用
%g
格式说明符来编辑尾随零。I believe you want the
%g
format specifier to redact trailing zeros.并不是真正的四舍五入,但是您是否尝试过
%f
它应该只显示所需的位数,而不是填充数字。我上面的答案是错误的,
正如其他人所说, %g
是正确的方法。字符串格式化程序的文档也应该有所帮助。 http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265
Not really rounding, but have you tried just
%f
it should only show the number of digits required rather then padding out the number.My answer above is wrong,
%g
as others has stated is the right way to go.The documentation for string formatters should help too. http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265
以下是您可以使用的所有格式说明符的列表...
Here is a list of all the format specifiers that you can use...