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

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

    The quick "in a nut shell" most obvious answer seems like:

    #define N_DECIMAL_POINTS_PRECISION (1000) // n = 3. Three decimal points.
    
    float f = 123.456;
    int integerPart = (int)f;
    int decimalPart = ((int)(f*N_DECIMAL_POINTS_PRECISION)%N_DECIMAL_POINTS_PRECISION);
    

    You would change how many decimal points you want by changing the N_DECIMAL_POINTS_PRECISION to suit your needs.

提交回复
热议问题