Search code examples
cvariablestype-promotion

Multiplying float With Large Numbers Simply Appending Numbers Together


I am attempting to convert float values of MB, GB, and TB to bytes, but I am having issues multiplying a base amount of space (say, 500 GB) by a large value to convert them.

I believe it is a data type error, yet I can't seem to figure it out. I tried looking at the order of promotion, yet following that logic didn't seem to work. When my program tries to multiply 500 * 10000000000, I get 1000000000499999997952.000000 (or something similar depending on variable types).

long factor = 10000000000;
float capacity = 500;
double result = capacity * factor;
fprint("%lf", result);

It should output 5000000000000, but I get 1000000000499999997952.000000 instead. I don't think the variable types are right, but nothing I try seems to aid this issue.


Solution

  • #include <stdio.h>
    
    int main()
    {
        unsigned long long factor = 10000000000;
        float capacity = 500.0f;
        double result = capacity * factor;
        double result1 = (double)capacity * factor;
    
        printf("result = %f\n result1 = %f\n", result, result1);
    
        return 0;
    }
    

    and the result

    result = 4999999913984.000000
    result1 = 5000000000000.000000