0

I'm working on pset2 with cash.

But something interesting is happening

if input is 6.876 and i printf that value of that variable I get 6.88 instead of 6.87. How can I get 6.87 instead of round 6.88? my code:

#include <math.h>
#include <stdio.h>
#include <cs50.h>

int main (void)
{
    float cash;
    do
    {
    cash = get_float ("cash: ");
    }
    while (cash < 0);

    printf("%.2f\n", cash);
}
1

I know of two ways, but neither can be done through how printf works.

The way I would do it would be to multiply the value by 100 and cast it to an int, which would cut off any remaining decimal values. Then, I would return it to a float and divide by 100. So, printf(%.2f\n", (float((int)(cash * 100))) / 100.0. You might be able to do this without explicitly casting it back to a float, but I never risk it.

You could also use the trunc function from the math.h library. This would be similar in use to the method above: printf("%.2f\n", (trunc(cash*l00)/100));

Either of these should work, but I prefer using the first option as it doesn't require any extra knowledge about how an outside function works, and is therefore more obvious to anyone else that reads the code.

2
  • But what is the accutally rounds it and why?? is it %.2f? or printf? For some reson i cant see that value in debuger.
    – arianwww
    Feb 5 at 19:16
  • When printf is given a floating-point value that is longer than the specified precision (two decimal places in this instance), it rounds the value to the specified length. So, the rounding is happening because your float has more than the two decimal places you want to be printed and printf does not "cut off" the rest, but rounds the number to provide the closest value in output--6.88 is closer to 6.876 than 6.87, making it more precise. Hope that makes sense. Feb 5 at 19:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .