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.
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.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
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: