C: convert double to float, preserving decimal point precision

后端 未结 3 2034
野性不改
野性不改 2020-12-16 12:05

i wanted to convert double to float in C, but wanted to preserve the decimal point exactly as possible without any changes...

for example, let\'s say i have

相关标签:
3条回答
  • 2020-12-16 12:15

    Floating point numbers are represented in scientific notation as a number of only seven significant digits multiplied by a larger number that represents the place of the decimal place. More information about it on Wikipedia:

    http://en.wikipedia.org/wiki/Floating_point

    0 讨论(0)
  • 2020-12-16 12:19

    A float generally has about 7 digits of precision, regardless of the position of the decimal point. So if you want 5 digits of precision after the decimal, you'll need to limit the range of the numbers to less than somewhere around +/-100.

    0 讨论(0)
  • 2020-12-16 12:30

    float and double don't store decimal places. They store binary places: float is (assuming IEEE 754) 24 significant bits (7.22 decimal digits) and double is 53 significant bits (15.95 significant digits).

    Converting from double to float will give you the closest possible float, so rounding won't help you. Goining the other way may give you "noise" digits in the decimal representation.

    #include <stdio.h>
    
    int main(void) {
        double orig = 12345.67;
        float f = (float) orig;
        printf("%.17g\n", f); // prints 12345.669921875
        return 0;
    }
    

    To get a double approximation to the nice decimal value you intended, you can write something like:

    double round_to_decimal(float f) {
        char buf[42];
        sprintf(buf, "%.7g", f); // round to 7 decimal digits
        return atof(buf);
    }
    
    0 讨论(0)
提交回复
热议问题