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

后端 未结 14 1999
旧巷少年郎
旧巷少年郎 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 
    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
    

提交回复
热议问题