Is there a way to round floating points to 2 points? E.g.: 3576.7675745342556
becomes 3576.76
.
Using std::ios_base::precision You could use std::ostringstream with the precision specifier as for std::cout . With C, you can achieve the same with the %. 2f format string in the printf() function. That's all about restricting a floating-point value to two places after the decimal point in C++.
Floating-point decimal values generally do not have an exact binary representation. This is a side effect of how the CPU represents floating point data. For this reason, you may experience some loss of precision, and some floating-point operations may produce unexpected results.
As a result, they do not represent all of the same values, are not binary compatible, and have different associated error rates. Because of a lack of guarantees on the specifics of the underlying floating-point system, no assumptions can be made about either precision or range.
round(x * 100) / 100.0
If you must keep things floats:
roundf(x * 100) / 100.0
Flexible version using standard library functions:
double GetFloatPrecision(double value, double precision)
{
return (floor((value * pow(10, precision) + 0.5)) / pow(10, precision));
}
If you are printing it out, instead use whatever print formatting function available to you.
In c++
cout << setprecision(2) << f;
For rounding to render to GUI, use std::ostringstream
Multiply by 100, round to integer (anyway you want), divide by 100. Note that since 1/100 cannot be represented precisely in floating point, consider keeping fixed-precision integers.
For those of you googling to format a float to money like I was:
#include <iomanip>
#include <sstream>
#include <string>
std::string money_format (float val)
{
std::ostringstream oss;
oss << std::fixed << std::setfill ('0') << std::setprecision (2) << val;
return oss.str();
}
// 12.3456 --> "12.35"
// 1.2 --> "1.20"
You must return it as a string. Putting it back into a float will lose the precision.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With