如何获得双精度数中包含的位数?
我试图获取以下双精度值中的位数:56.46855976,而不使用将其转换为字符串(只需将“.”替换为“”)。
有人有什么想法吗?
I'm trying to get the number of digits in the following double value: 56.46855976 without using converting it to a string (and simply replacing the "." with a "").
Anybody got any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
计算必须将这个数字除以 10 的次数,直到它小于 1 ->;给出小数点前的数字。
然后计算必须将原始数字乘以 10 的频率,直到它等于 Math.Floor-结果 ->这给你小数点后面的数字。
添加。高兴吧。
编辑:正如乔伊指出的那样,其中存在一些不确定性。预先定义最大位数,这样就不会创建无限循环。
另一方面 - “丹麦的海岸有多长?”......
Count how often you must divide the number by 10 until it's smaller than 1 -> that gives you the digits before the decimal point.
Then count how often you must multiply the original number by 10 until it equals the Math.Floor-result -> that gives you the digits behind the decimal points.
Add. Be glad.
Edit: As Joey points out, there is some uncertianity in it. Define a maximum number of digits beforehand so you don't create an infinite loop.
On the other hand - "How long is the coast of Denmark?"...
正如马丁提到的,数到 的右侧。毫无意义。
测试:
As Martin mentioned, counting to the right of the . is pointless.
Tests:
转换为字符串可能是最好的选择。请记住,
double
在内部以 Base 2 表示。因此,您看到的十进制表示形式只是实际存储值的近似值(最大 253 的整数除外),它是 2 的各个幂的总和。因此,尝试计算出小数位数从二进制表示中提取数字当然不是一项简单或微不足道的任务 - 特别是因为该框架还可能应用舍入来使 3.999999999998 这样的数字看起来像 4.0,因为它们看起来比实际具有更高的精度。
Converting to a string might be the best option you have. Remember that
double
s are represented in Base 2 internally. Therefore the decimal representation you see is only an approximation of the actually stored value (except for integers up to 253) which is a sum of individual powers of 2.So trying to figure out the number of decimal digits from the binary representation is certainly not an easy or trivial task – especially since the framework might also apply rounding to make numbers like 3.999999999998 appear like 4.0 since they appear to have more precision than there actually is.
对于“右边的数字”(即数字“顺序”),在任何静态类中添加此扩展方法:
对于更一般的情况:“右边的数字”和“左边的数字”(定义为有效数字的数量,即,最低的非零小数位):
测试:
For "digits at rigth" (i.e. number "order"), adds this extension method in any static class:
For the more gereral case: "digits at rigth" and "digits at left" (defined as the number of significant digits, i.e., the lowest non-zero decimal place):
Testing: