How to separate float into integer and fractional part?

I am ready to do the exact operations, and for this I need a way to divide the floating-point number into an integer and a fractional part. Is there any way to do this?

+6
source share
2 answers

There is a function included in the math.h library called modf. With this function you can do what you are trying to do.

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); return fractional; } 

Output:

 Floating: 3.40 Integer: 3 Fractional: 0.40 

Please note: it is better to use double in most cases, using a float , noteter that double consumes more memory, and then float (often 4: 8 bytes). Also, if you need more accurate output from large floating numbers, you can use printf %e instead of %g , which uses a shorter representation of the floating point number. I would use %e for accuracy after all.

+17
source

I had the idea 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 looking for :).

0
source

Source: https://habr.com/ru/post/970178/


All Articles