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

后端 未结 3 961
天涯浪人
天涯浪人 2021-01-04 18:17

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?

相关标签:
3条回答
  • 2021-01-04 19:03

    A thought crossed my mind to separate them with some logic :

        #include <iostream>
    
    using namespace std;
    int main()
        {
        double fr,i,in,num=12.7;
        for(i=0;i<num;i++)
        {
            fr=num-i;
            }
            cout<<"num: "<<num;
    cout<<"\nfraction: "<<fr;
    in=num-fr;
    cout<<"\nInteger: "<<in;
        }
    

    Hope this was what you were searching for:) .

    0 讨论(0)
  • 2021-01-04 19:08

    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.

    0 讨论(0)
  • 2021-01-04 19:10

    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);
    }
    
    0 讨论(0)
提交回复
热议问题