Let us consider the following piece of code:
#include <stdio.h>
int main()
{
float dollars;
int cents;
dollars = 159.95;
cents = dollars*100;
printf("Dollars:%f\tCents:%d\n",dollars,cents);
return 0;
}
The output would be:
Dollars: 159.949997 Cents:15995
I understand that 159.95 does not have a precise representation in binary. But I'm not sure why the value 15995 is stored in the variable cents.
I was wondering if in these cases it would be desirable to use round in the expression, in this way:
cents = round(dollars*100);
What is the best practice for dealing with those cases?
Please, notice that this example using currency is just an example. I would like to discuss the general case. Is there any general best practice for doing this kind of operation?