Search code examples
cnumbersfractionsdecimal-point

How to split a number into two at the decimal point in C?


I'm trying to split a number in C into two at the decimal point. For example, let's say the number is 1.5, then I want to split it into 1 and 0.5. How can I do this?


Solution

  • You can use modf() from math.h library:

    #include <stdio.h>
    #include <math.h>
    
    int main () {
    
       double value, fractional, integer;
    
       value = 8.123456;
       fractional = modf(value, &integer);
    
       printf("Integral part = %lf\n", integer);
       printf("Fraction Part = %lf \n", fractional);
    
       return(0);
    }
    

    Sample from tutorialspoint.com