Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to round a double to n decimals? [duplicate]

Tags:

c++

math

rounding

I am trying to find a round function in the standard library but I didn't see one. Is there any way to round a double to n decimals in c++?

like image 937
user1285419 Avatar asked Dec 16 '22 02:12

user1285419


1 Answers

C++11 has std::round in <cmath>.

Without that you can use std::floor and std::ceil on adjusted numbers. E.g. std::floor(n * 100 + 0.5)/100 to round to two decimal places.

Although it should be noted that rounding isn't entirely trivial; There are complications such as choosing to round toward zero, toward negative infinity, round to even, etc. If you're writing programs for production be sure you understand the rounding requirements for your domain.

like image 118
bames53 Avatar answered Jan 07 '23 10:01

bames53