如何将数字四舍五入到一定范围内?
我有一个像这样的值:
421.18834
并且我必须使用如下所示的掩码正确地对其进行数学舍入:
0.05
0.04
0.1
例如,如果掩码是 0.04,我必须获取值 421.20
,因为 . 18 比 0.16 更接近 0.20。
我用谷歌发现的所有功能都不起作用。
你能帮我吗?
I have a value like this:
421.18834
And I have to round it mathematical correctly with a mask which can look like this:
0.05
0.04
0.1
For example, if the mask is 0.04, i have to get the value 421.20
, because .18 is nearer at .20 than .16.
All functions that I found using Google didn't work.
Can you please help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不需要特殊的功能。将原始数字乘以(1/掩码),将其四舍五入为小数,然后再次除以相同的因子。
0.05 的示例
<前><代码>系数 = 1/0.05 = 20
421.18834 * 20 = 8423.7668
整数(8423.7668)= 8424
8424.0 / 20.0 = 421.20
0.01 的示例
<前><代码>系数 = 1/0.1 = 10
421.18834 * 10 = 4211.8834
整数(4211.8834)= 4212
4212.0 / 10.0 = 421.20
You don't need a special function. You multiply your original number by (1/mask), you round it to a decimal and you divide again by the same factor.
Example with 0.05
Example with 0.01
与您可能在这里得到的有关乘法和除法的所有答案相反,您无法准确地执行此操作,因为浮点没有小数位。需要转换为十进制基数然后四舍五入。 BigDecimal 就是这样做的。
Contrary to all the answers you will probably get here about multiplying and dividing, you can't do this accurately because floating point doesn't have decimal places. To need to convert to a decimal radix and then round. BigDecimal does that.
fredley 和 Matteo 都假设舍入因子本身就是 100。对于 0.06 或 0.07 这样的因子,这是一个错误的假设。
这是我的 Java 例程:
Both fredley and Matteo make the assumption that the rounding factor is itself a factor of 100. For factors like 0.06 or 0.07, this is an incorrect assumption.
Here's my Java routine: