How to extract the decimal part from a floating point number in C?

后端 未结 14 1890
旧巷少年郎
旧巷少年郎 2020-11-27 04:04

How can we extract the decimal part of a floating point number and store the decimal part and the integer part into two separate integer variables?

相关标签:
14条回答
  • 2020-11-27 04:33

    Here is another way:

    #include <stdlib.h>
    int main()
    {
        char* inStr = "123.4567";         //the number we want to convert
        char* endptr;                     //unused char ptr for strtod
    
        char* loc = strchr(inStr, '.');
        long mantissa = strtod(loc+1, endptr);
        long whole = strtod(inStr, endptr);
    
        printf("whole: %d \n", whole);     //whole number portion
        printf("mantissa: %d", mantissa);  //decimal portion
    
    }
    

    http://codepad.org/jyHoBALU

    Output:

    whole: 123 
    mantissa: 4567
    
    0 讨论(0)
  • 2020-11-27 04:34

    Try this:

    int main() {
      double num = 23.345;
      int intpart = (int)num;
      double decpart = num - intpart;
      printf("Num = %f, intpart = %d, decpart = %f\n", num, intpart, decpart);
    }
    

    For me, it produces:

    Num = 23.345000, intpart = 23, decpart = 0.345000
    

    Which appears to be what you're asking for.

    0 讨论(0)
  • 2020-11-27 04:40

    You use the modf function:

    double integral;
    double fractional = modf(some_double, &integral);
    

    You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.

    0 讨论(0)
  • 2020-11-27 04:40

    Maybe the best idea is to solve the problem while the data is in String format. If you have the data as String, you may parse it according to the decimal point. You extract the integral and decimal part as Substrings and then convert these substrings to actual integers.

    0 讨论(0)
  • 2020-11-27 04:40

    Suppose A is your integer then (int)A, means casting the number to an integer and will be the integer part, the other is (A - (int)A)*10^n, here n is the number of decimals to keep.

    0 讨论(0)
  • 2020-11-27 04:41

    I created a subroutine one using a double float, it returns 2 integer values.

    
    void double2Ints(double f, int p, int *i, int *d)
    { 
      // f = float, p=decimal precision, i=integer, d=decimal
      int   li; 
      int   prec=1;
    
      for(int x=p;x>0;x--) 
      {
        prec*=10;
      };  // same as power(10,p)
    
      li = (int) f;              // get integer part
      *d = (int) ((f-li)*prec);  // get decimal part
      *i = li;
    }
    
    void test()
    { 
      double df = 3.14159265;
      int   i,d;
      for(int p=2;p<9;p++)
      {
        double2Ints(df, p, &i,&d); printf("d2i (%d) %f = %d.%d\r\n",p, df,i,d);
      }
    }
    
    
    0 讨论(0)
提交回复
热议问题