将 Objective-C 浮点数四舍五入到最接近的 0.05
我想将以下浮点数四舍五入到最接近的 0.05。
449.263824 --> 449.25
390.928070 --> 390.90
390.878082 --> 390.85
我怎样才能做到这一点?
I want to round the following floating point numbers to the nearest 0.05.
449.263824 --> 449.25
390.928070 --> 390.90
390.878082 --> 390.85
How can I accomplish that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为了匹配您问题中的输出,您可以执行以下操作:
示例:
The match the output in your question, you can do the following:
Example:
有 round() 功能。我认为你需要这样做:
与所有浮点运算一样,由于 1/5 不能直接表示为二进制值,因此你会看到奇怪的不完全精确的结果。如果你不喜欢这样,你可以使用 NSDecimalNumber 的 -decimalNumberByRoundingAccordingToBehaviour: 方法,但会慢一点。
There's the round() function. I think you need to do this:
As with all floating point operations, since 1/5 is not directly representable as a binary value, you'll see bizarre not quite exact results. If you don't like that, you can use NSDecimalNumber's -decimalNumberByRoundingAccordingToBehaviour: method but it'll be a bit slower.
我知道问题已得到解答,但我使用了以下代码:
例如:
I know the question is answered but I used the following code:
For example:
您可以使用 NSNumberFormatter< /a> 进行舍入,并通过
NSNumberFormatterRoundingMode
选项之一指定所需的舍入。 (在上面的类参考中搜索“NSNumberFormatterRoundingMode”以查看默认值。)但是,正如 @Jesse 在对您的问题的评论中指出的那样,在您的示例中似乎没有任何标准的舍入形式假如。
You could use an NSNumberFormatter to carry out rounding and indeed to specify the rounding you require via one of the
NSNumberFormatterRoundingMode
options. (Search for "NSNumberFormatterRoundingMode" in the above class reference to see the defaults.)However, as @Jesse states in the comment on your question, there doesn't seems to be any standard form of rounding going on in the examples you're provided.
如果它四舍五入到最接近的 x,那么您可以选择:
事实上,并不完全清楚您想要什么。
If it were round to the nearest x, then you could go with:
As it is, it isn't entirely clear what you want.
使用
地板
:Use
floor
: