I had to do the following to avoid floating point imprecision, but it seems inelegant. There must be a better/simpler way I'm not thinking of?

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

int main(void)
    float moneyfloat;
        printf("How much money you got?\n");
        moneyfloat = GetFloat();
    while (moneyfloat <= 0);

    int money = (int) roundf(moneyfloat * 100);

1 Answer 1


No, that's exactly right. Doesn't get any cleaner than that!

  • Why is that right? I can't understand how the rounding or casting is supposed to work no matter how many times I watched the walkthrough and the typecasting video. If the change is less than 1.00 ( like 0.41), why are we multiplying by 100? All I keep thinking is 0.41 then becomes 41, which means $41 and not $0.41 which is an entirely different amount of coins!
    – Jo Harr
    Sep 9, 2015 at 19:07
  • The "rounding" functions will round a number to the decimal point, not to a particular digit to the left or right, so a rounded number becomes a whole number.. The reason that we multiply by 100 is that all of the coins are based on whole numbers of cents. It's kind of a smallest common denominator thing here. So, while the original number is in dollars and cents, it is more precisely in dollars and fractions of dollars. By multiplying by 100, we are converting everything to cents. At that point, there are no partials, no fractions, only whole numbers, i.e., integers left to deal with.
    – Cliff B
    Sep 9, 2015 at 21:22

You must log in to answer this question.

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