Rounding doubles - .5 - sprintf

前端 未结 5 779
遥遥无期
遥遥无期 2021-01-11 20:15

I\'m using the following code for rounding to 2dp:

sprintf(temp,\"%.2f\",coef[i]); //coef[i] returns a double

It successfully rounds 6.666

相关标签:
5条回答
  • 2021-01-11 20:30

    You could also do this (saves multiply/divide):

    printf("%.2f\n", coef[i] + 0.00049999);
    
    0 讨论(0)
  • 2021-01-11 20:37

    How about this for another possible solution:

    printf("%.2f", _nextafter(n, n*2));
    

    The idea is to increase the number away from zero (the n*2 gets the sign right) by the smallest possible amount representable by floating point math.

    Eg:

    double n=5.555;
    printf("%.2f\n", n);
    printf("%.2f\n", _nextafter(n, n*2));
    printf("%.20f\n", n);
    printf("%.20f\n", _nextafter(n, n*2));
    

    With MSVC yields:

    5.55
    5.56
    5.55499999999999970000
    5.55500000000000060000
    
    0 讨论(0)
  • 2021-01-11 20:39

    The number 5.555 cannot be represented as an exact number in IEEE754. Printing out the constant 5.555 with "%.50f" results in:

    5.55499999999999971578290569595992565155029300000000
    

    so it will be rounded down. Try using this instead:

    printf ("%.2f\n",x+0.0005);
    

    although you need to be careful of numbers that can be represented exactly, since they'll be rounded up wrongly by this expression.

    You need to understand the limitations of floating point representations. If it's important that you get accuracy, you can use (or code) a BCD or other decimal class that doesn't have the shortcoming of IEEE754 representation.

    0 讨论(0)
  • 2021-01-11 20:45

    It seems you have to use math round function for correct rounding.

    printf("%.2f %.2f\n", 5.555, round(5.555 * 100.)/100.);
    

    This gives the following output on my machine:

    5.55 5.56
    
    0 讨论(0)
  • 2021-01-11 20:46

    This question is tagged C++, so I'll proceed under that assumption. Note that the C++ streams will round, unlike the C printf family. All you have to do is provide the precision you want and the streams library will round for you. I'm just throwing that out there in case you don't already have a reason not to use streams.

    0 讨论(0)
提交回复
热议问题