How to separate float into an integer and a fractional part?
One other way using type cast.
#include <stdio.h>
#include <math.h>
void main()
{
float a = 3.4;
float a_frac = a - (int) a;
float a_int = a - a_frac;
printf("Number = %f, Integer = %f, Fraction = %f", a, a_frac, a_int);
}
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 <stdio.h>
#include <math.h>
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.