Rounding doubles - .5 - sprintf

前端 未结 5 826
遥遥无期
遥遥无期 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: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
    

提交回复
热议问题