Avoid changing the type used to represent money as done here between float
and int
.
float totalAmount;
int totalAmountCents;
...
totalAmountCents = totalAmount * 100;
Money has special issues involving exactness, range and functions that do not simply apply to integers like complex tax and interest rate calculations. These issues are aggravated with casual type conversions.
For learning, start with int
or long
of the smallest unit of money and pay special attention to rounding.
If floating point type is required, rarely is float
a good choice. Do not use integer conversion to round. Use rint()
or round()
double totalAmount;
double totalAmountCents;
...
totalAmountCents = rint(totalAmount * 100);
If a conversion to int
is absolutely required, round using a floating point rounding function and then convert or use lrint()
.
#include <math.h>
totalAmountCents = rint(totalAmount * 100);
int iCents = (int) totalAmountCents;
// or
long LCents = lrint(totalAmount * 100);
solved Converting float to int effectively