开发者

Truncating double without rounding in C

Lets consider we have a double R = 99.999999; (which may be obtained by a result of some other computation),now the desired output i开发者_如何学JAVAs 99.99

I tried using printf("%.2lf",R); but it's rounding off the value.How to get the desired output ? (preferably using printf)


#include <math.h>
...
    printf("%.2f", floor(100 * R) / 100);


All you have to do is subtract .005 from the number and magically printf will behave as you wish: always round down.


sprintf it into a buffer, and then put the NUL char two bytes past the '.'

Then printf your final string using the intermediate one.


If you have it, use fmod() to chop the tail of the double:

double rounded = R - fmod(R, 0.01);
// Now just print rounded with what you were using before

This has the advantage of working the same if R is positive or negative.


What about using double trunc(double) from GLibC?


Can you multiply by 100 and then truncate to an integer? Then you could format the result like one would with dollars and cents. Simply dividing by 100 might land you back at square one due to floating-point representation issues.


Another solution, using casts:

...
printf("%.2lf", (double) ((int) (R * 100)) / 100);


Another way, truly sign agnostic: printf("%d.%d\n", (int) r ,abs((int)(r*100) % 100));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜