C:将 double 转换为 float,保留小数点精度
我想在 C 中将 double 转换为 float,但想尽可能准确地保留小数点而不进行任何更改...
例如,假设我
double d = 0.1108;
double dd = 639728.170000;
double ddd = 345.2345678
现在纠正了我,如果我错了,我知道浮点精度约为 5点后的数字。我可以得到点后的这五个数字,就像双精度数字一样吗?这样上面的结果如下:
float f = x(d);
float ff = x(dd);
float fff = x(ddd);
printf("%f\n%f\n%f\n", f, ff, fff);
它应该打印
0.1108
639728.17000
345.23456
精度限制(我假设为 5)被截断后的所有数字。
i wanted to convert double to float in C, but wanted to preserve the decimal point exactly as possible without any changes...
for example, let's say i have
double d = 0.1108;
double dd = 639728.170000;
double ddd = 345.2345678
now correct me if i am wrong, i know that floating point precision is about 5 numbers after the dot. can i get those five numbers after the dot exactly as the double had it? so that above results as follows:
float f = x(d);
float ff = x(dd);
float fff = x(ddd);
printf("%f\n%f\n%f\n", f, ff, fff);
it should print
0.1108
639728.17000
345.23456
all digits after the precision limit (which i assume as 5) would be truncated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
float
和double
不存储小数位。它们存储二进制位:float
是(假设IEEE 754)24个有效位(7.22个十进制数字),而double是53个有效位(15.95个有效位)。从
double
转换为float
将为您提供最接近的float
,因此舍入对您没有帮助。反之则可能会给你带来十进制表示中的“噪音”数字。要获得您想要的精确十进制值的 double 近似值,您可以编写如下内容:
float
anddouble
don't store decimal places. They store binary places:float
is (assuming IEEE 754) 24 significant bits (7.22 decimal digits) and double is 53 significant bits (15.95 significant digits).Converting from
double
tofloat
will give you the closest possiblefloat
, so rounding won't help you. Goining the other way may give you "noise" digits in the decimal representation.To get a
double
approximation to the nice decimal value you intended, you can write something like:无论小数点的位置如何,
float
通常具有大约 7 位精度。因此,如果您想要小数点后 5 位的精度,则需要将数字范围限制为小于 +/-100 左右。A
float
generally has about 7 digits of precision, regardless of the position of the decimal point. So if you want 5 digits of precision after the decimal, you'll need to limit the range of the numbers to less than somewhere around +/-100.浮点数以科学记数法表示为只有七个有效数字的数字乘以代表小数点位置的较大数字。
维基百科上有关它的更多信息:
http://en.wikipedia.org/wiki/Floating_point
Floating point numbers are represented in scientific notation as a number of only seven significant digits multiplied by a larger number that represents the place of the decimal place.
More information about it on Wikipedia:
http://en.wikipedia.org/wiki/Floating_point