C:double转换成浮动,preserving小数点precision [英] C: convert double to float, preserving decimal point precision
问题描述
我想转换双浮在C,但究竟尽可能想preserve小数点不作任何改变...
i wanted to convert double to float in C, but wanted to preserve the decimal point exactly as possible without any changes...
例如,假设我有
double d = 0.1108;
double dd = 639728.170000;
double ddd = 345.2345678
现在纠正我,如果我错了,我知道,浮点precision是点后约5个号码。我可以得到这些五个数字的小数点后完全按双了吧?使上述结果如下:
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);
它应该打印
0.1108
639728.17000
345.23456
在precision限制之后,所有的数字(我假定为5)将被截断。
all digits after the precision limit (which i assume as 5) would be truncated.
推荐答案
浮动
和双击
不存储小数。他们店里二进制的地方:浮动
终止(假设IEEE 754)24显著位(7.22小数位数)和双53显著位(15.95显著位)。
float
and double
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).
从转换双
到浮动
会给你最接近的可能浮动
,所以四舍五入不会帮你。 Goining其他方式可能会给你在小数重presentation噪声的数字。
Converting from double
to float
will give you the closest possible float
, so rounding won't help you. Goining the other way may give you "noise" digits in the decimal representation.
#include <stdio.h>
int main(void) {
double orig = 12345.67;
float f = (float) orig;
printf("%.17g\n", f); // prints 12345.669921875
return 0;
}
要获得双击
逼近你预期的美好十进制值,你可以写这样的:
To get a double
approximation to the nice decimal value you intended, you can write something like:
double round_to_decimal(float f) {
char buf[42];
sprintf(buf, "%.7g", f); // round to 7 decimal digits
return atof(buf);
}
这篇关于C:double转换成浮动,preserving小数点precision的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!