I am willing to cast precise operations and for that purpose I need a way to seperate a float number into an integer and a fractional part. Is there any way for this?
There is a function included in math.h
library called modf
With this function you can do just what are you trying to.
Example:
#include
#include
double ftof ()
{
double floating = 3.40, fractional, integer;
fractional = modf(floating, &integer);
printf ("Floating: %g\nInteger: %g\nFractional: %g", floating, integer, fractional); // when using printf, there are no floats
return fractional;
}
Output:
Floating: 3.40
Integer: 3
Fractional: 0.40
Note that using double
in most of the cases is better than using float
, despite that double
consumes twice the memory of float
(4:8 bytes) hence the increased range and accuracy. Also in case you need more precise output from
bigger floating numbers when printing, you can try the printf()
exponent format specifier %e
instead of %g
which only uses the
shortest representation of the floating decimal.