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

后端 未结 3 974
天涯浪人
天涯浪人 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: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 
    #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.

提交回复
热议问题