Is there a way to round floating points to 2 points? ex: 3576.7675745342556 becomes 3576.76.
Thanks
Is there a way to round floating points to 2 points? ex: 3576.7675745342556 becomes 3576.76.
Thanks
round(x * 100) / 100.0
If you must keep things floats:
roundf(x * 100) / 100.0
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.
Don't do it. You have no good reason to lose the precision in your calculations. (Also if this is performance intensive loop, keep in mind the cast from float to int as mentioned above flushes the pipeline cache).
The only reason you would want to do that is when you are printing it out. In which case instead use whatever print formatting function available to you.
In c++
cout << setprecision(2) << f;
Edit: In the case you need to round for converting to a string and passing to a method, the numerical method is fine. However, std::ostringstream can help you here as well.
Don't use floats. Use integers storing the number of cents and print a decimal point before the last 2 places if you want to print dollars. Floats are almost always wrong for money unless you're doing simplistic calculations (like naive economic mathematical models) where only the magnitude of the numbers really matters and you never subtract nearby numbers.