Search code examples
cstringfloating-pointtype-conversiondouble

How to convert fractional part of double to string or fractional part of double to integer using c without changing exact value


Is there a way to convert double into string without changing the value? or is there a way to truncate fractional part of a number to certain decimal precision and store in long? convertions seem to round up or down which will not work in my case.

double t = 8.299877766666;

either string which holds exact same value or truncated to certain decimal precision for example string which holds "299877766666" or "0.29987"?


Solution

  • Not sure what you tried, but the naive thing works for me:

    uint64_t frac_dig(double x, int digits)
    {
        // 20 non-zero digits will overflow a 64bit integer
        assert(0 < digits && digits < 20);
    
        // remove non-fractional digits, and strip off sign
        x = fabs(fmod(x, 1));
    
        uint64_t result = 0;
    
        while (digits-- > 0) {
            x *= 10;
            result *= 10;
            int i = x;
            result += i;
            x -= i;
        }
    
        return result;
    }
    

    testing via

        double t = -8.299877766666;
        printf("%.24f  = %lu\n", t, frac_dig(t, 19));
    

    prints out

    -8.299877766666000411532877  = 2998777666660004115
    

    note that floating point values are base-2 encoded not decimal. this might be causing some of your "rounding issues". for example, the nearest value that can be represented by a double is slightly larger than the value in your question, as shown when printing out extra digits via printf.