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?
Thank you all. If you want to convert a float to two ints, subtract the truncated int value from the float, then multiply the remaining fraction by 10000.
Using the modulo ( % ) operator If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.
For example, one could multiply it by 100 (so that 21.83 becomes 2183), then find the remainder on division by 100 (so that 2183 becomes 83), then divide by 100 (so that 83 becomes 0.83). Or, if what you have is the floor function, you could find x−⌊x⌋, for example: 21.83−⌊21.83⌋=0.83.
Cast to an int value: When a float value is cast to an int value, it loses the fractional part of the number, regardless of the value. $int_value = (int) 2.87; // $int_value = 2; Notice how the . 87 is lost when 2.87 is cast to an 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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With