floating point - How can I avoid this float number rounding issue in C++? -
with below code, result "4.31 43099".
double f = atof("4.31"); long ff = f * 10000l; std::cout << f << ' ' << ff << '\n'; if alter "double f" "float f". expected result "4.31 43100". not sure if changing "double" "float" solution. there solution assure "43100"?
the problem floating point inexact nature when talking decimal numbers. decimal number can rounded either or downwards when converted binary, depending on value closest.
in case want create sure if number rounded down, it's rounded instead. adding smallest amount possible value, done nextafter function if have c++11:
long ff = std::nextafter(f, 1.1*f) * 10000l; if don't have nextafter can approximate numeric_limits.
long ff = (f * (1.0 + std::numeric_limits<double>::epsilon())) * 10000l; i saw comment utilize 4 decimal places, simpler less robust:
long ff = (f * 1.0000001) * 10000l; c++ floating-point floating-point-conversion
No comments:
Post a Comment