I wanted to know what would be the fastest approach of comparing floats to three decimal places.Say I have something like this
float lhs = 2.567xxxx
float rh
Convert the float values to strings with the full number of places (std::numeric_limits), then truncate the string to 3 decimal places, and compare the resulting strings:
std::string convert(float value, int places) {
if (value == 0) {
return "0";
}
int digits(std::numeric_limits::digits10 - std::log(value) / std::log(10));
digits = std::max(0, digits);
std::ostringstream out;
out << std::fixed << std::setprecision(digits) << value;
std::string rc(out.str());
return places < digits? rc.substr(0, rc.size() - (digits - places)): rc;
}
bool compare(float f1, float f2) {
return convert(f1, 3) == convert(f2, 3);
}
The various comparisons proposed multiplying by 100 or 1000 don't work because they will do binary rather than decimal rounding. You could try to add 0.5 after multiplying and before truncating to int but there are cases (although few) where this approach still fails. The conversion above, however, does the right thing as long as you don't end up with more than std::numeric_limits digits. Trying to deal with more decimal digits than this number will fail because the float can't represent as many decimal digits correctly anyway.