It is not an issue of Qt, it is a matter of the internal representation of floating point numbers (base-2 based, not base-10 based). See Why not use Double or Float to represent currency? for some good background information.
If you rely on exact values, do not use floating point numbers, but store the integer and the fractional part of your number in separate integers, e.g.
int integ = 294;
int fraction = 4; /* assumption: one fractional digit */
and then use integer arithmetic only for your calculations.
See Is there a library class to represent floating point numbers? for links to various existing libraries for these kind of calculations.
Based on the feedback from the comments, I suggest to parse the String into the integer and fractional part, for example like this:
struct Money {
int integ;
int fract;
};
Money parseMoney(const QString& input) {
QString cleanInput = input;
Money result = {0,0};
// remove group separators
QLocale locale = QLocale::system();
cleanInput.remove(locale.groupSeparator());
// convert to money
QStringList parts = cleanInput.split(locale.decimalPoint());
if (parts.count() == 1) {
result.integ = parts[0].toInt();
} else if (parts.count() == 2) {
result.integ = parts[0].toInt();
result.fract = parts[1].toInt() * 10;
} else {
// error, not a number
}
return result;
}
The assumption is that the input is a string which is formatted according to the current locale, e.g. if the group separator is ',' the decimal point is '.' and the input string is "3,294.4" the result in Money would be {3294, 40}.