Coder
Coder

Reputation: 101

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 is 99.99

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

Upvotes: 10

Views: 9702

Answers (8)

Donal Fellows
Donal Fellows

Reputation: 137567

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.

Upvotes: 2

frankc
frankc

Reputation: 11473

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

Upvotes: 0

Juliano
Juliano

Reputation: 811

Another solution, using casts:

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

Upvotes: 0

Michael Kristofik
Michael Kristofik

Reputation: 35188

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.

Upvotes: 0

frankc
frankc

Reputation: 11473

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

Upvotes: 4

Hans Passant
Hans Passant

Reputation: 941465

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

Upvotes: 12

Romain
Romain

Reputation: 12819

What about using double trunc(double) from GLibC?

Upvotes: 0

Ben Zotto
Ben Zotto

Reputation: 71008

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

Then printf your final string using the intermediate one.

Upvotes: 2

Related Questions