Is there a way to round floating points to 2 points? E.g.: 3576.7675745342556
becomes 3576.76
.
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
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.
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:
You must return it as a string. Putting it back into a float will lose the precision.
try use
std::cout<<std::setprecision(2)<<std::cout<<x;
should works and only 2 digit after the floating point appear.
Try this, it works perfectly
change some objects in it to see and learn the code.