Is there a way to round floating points to 2 points? E.g.: 3576.7675745342556 becomes 3576.76.
Is there a way to round floating points to 2 points? E.g.: 3576.7675745342556 becomes 3576.76.
I didn't find a clean answer that satisfied me since most of the clean answers assume you need to print the result which might not be the case if you are just storing some data to the acceptable resolution:
#include <sstream>
template<typename T>
T toPrecision(T input, unsigned precision)
{
static std::stringstream ss;
T output;
ss << std::fixed;
ss.precision(precision);
ss << input;
ss >> output;
ss.clear();
return output;
}
template<unsigned P, typename T>
T toPrecision(T input) { return toPrecision(input, P); }
// compile-time version
double newValue = toPrecision<2>(5.9832346739); // newValue: 5.98
// run-time version
double newValue = toPrecision(3.1415, 2); // newValue: 3.14
You can also add static checks for T and precision (in the case of the compile-time signature).
Try this, it works perfectly
float=3576.7675745342556;
printf("%.2f",float);
change some objects in it to see and learn the code.