Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate float into an integer and a fractional part?

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?

like image 492
TheMatrix Avatar asked Jun 02 '14 11:06

TheMatrix


People also ask

How do you separate float and int?

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.

How do you split a float value?

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.

How do you extract a fractional part of a number?

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.

When casting a float to an int what happens with the fractional portion of the float?

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 .


2 Answers

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.

like image 141
Edenia Avatar answered Sep 22 '22 12:09

Edenia


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);
}
like image 29
Vishwanath Hiremath 16210107 Avatar answered Sep 20 '22 12:09

Vishwanath Hiremath 16210107