doubles/printf & rounding

W

wombat

Is there a way to prevent rounding when using printf for print a
double/float?

Example:
double x=3.51;
printf("%.0f\n", x);



The output of this is 4, when I want it to be 3.

I've been surfing the net but I've been coming up empty. Big thanks for
any help.
 
J

Jim Langston

wombat said:
Is there a way to prevent rounding when using printf for print a
double/float?

Example:
double x=3.51;
printf("%.0f\n", x);



The output of this is 4, when I want it to be 3.

I've been surfing the net but I've been coming up empty. Big thanks for
any help.

printf("%.0f\n", x - 0.5);

This rounds down, but doesn't work correctly for negative x, in which case
you would want to add 0.5 (-3.51 - 0.5 = -4.01 so would be output as -4
instead of -3 as wanted).
 
J

James Kanze

Is there a way to prevent rounding when using printf for print a
double/float?
Example:
double x=3.51;
printf("%.0f\n", x);
The output of this is 4, when I want it to be 3.
I've been surfing the net but I've been coming up empty. Big thanks for
any help.

Nothing to do with printf: the same rules apply with the cleaner
iostreams. You can use floor() or ciel() to control how you
want rounded; C99 (and the next version of C++) add some more
(round() and trunc(), for example), which may already be
available with your compiler(s).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top