C++如何为浮点数设置固定的小数精度
我有一个返回双精度值的 API 调用。双精度数的小数长度可以从许多小数位到几个小数位不等(这一切都取决于执行器的状态)。该双精度代表执行器范围半径上的当前位置。 我对如此详细的数字不感兴趣,因为它给系统增加了很多噪音。 我一直在使用浮点数来节省空间,但我仍然有小数点长度为 6-8 位的浮点数。 我对地板或天花板不感兴趣,只是因为它不能完成我想要的工作。 例如,我有数字:
-2.05176
-0.104545
0.30643
0.140237
1.41205
-0.176715
0.559462
0.364928
无论如何,我希望将精度设置为小数点后两位。 我不是在谈论 std::cout 的输出精度,我知道如何设置它。我说的是浮点数的实际精度。即:我对具有 0.XX 格式和 0.XX00000000000 实际精度的浮点数感兴趣。 因此,将上面的列表转换为:
-2.05
-0.10
0.30
0.14
1.41
-0.17
0.55
0.36
我知道 boost 有一个数值转换模板,但我无法弄清楚如何使用较低的精度从浮点转换为浮点。有人可以帮忙吗?
I have an API call which returns a double. The double's decimal length can variate from many decimal places to a few (it all comes down to the state of an actuator). This double represents the current position on the range radius of an actuator.
I am not interested in such a detailed number, because it adds alot of noise to the system.
I've been using floats to save space, but still I have floats which have 6-8 decimal length.
I am not interested in floor or ceil, simply because it doesn't do the job i want.
For example, I have the numbers:
-2.05176
-0.104545
0.30643
0.140237
1.41205
-0.176715
0.559462
0.364928
I want the precision to be set to 2 decimal places no matter what.
I am NOT talking about the output precision on std::cout, I know how to set this. I am talking about the actual precision of the float. i.e: I am interested in floats who will have 0.XX format and 0.XX00000000000 actual precision.
Therefore transforming the above list to:
-2.05
-0.10
0.30
0.14
1.41
-0.17
0.55
0.36
I know boost has a numerical conversion template, but I cannot figure out how to convert from float to float using a lower precision. Can somebody please help ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你就不能把它绕圆吗?
Can't you just round it.
float 和 double 的精度取决于硬件。其他任何东西都需要用软件编码。
您可以尝试使用整数进行缩放:
The precision of float and double is down to the hardware. Anything else needs to be coded in software.
You could try scaling instead, working in ints: