With python3 round(x, n)
function we can round a float number to fixed decimal places. For example round(2.675, 2) = 2.67
, round(2.685, 2) = 2.69
. How can I implement such a function in C++? round(x*100.0)/100.0
gives different result with python3. Python's result is the same as printf("%.2f", 2.675)
. So one way is to store result in a char array using sprintf
function. Then convert the char array back to double. But this is very slow. Is there a better way? Thank you.
I was thinking since printf
function can do round automatically, is there a way to directly store the printf
function rounded result into a double variable?
edit: I would like to explain why I need to do this rounding to 2 decimal places. Because I was translating my colleague's python program to C++. In the python program he uses round(2.675, 2)=>2.67. And there is not a corresponding round function in C++ to give the exact same result. If the round result differ in 0.01 (if cpp_round(2.675, 2)=>2.68), it will trigger a totally different process in the computation.
Maybe it is easier to ask my colleague to change to a self-written round function. But since his programm is in use, it is difficult to for his to make this change.