Best way to approximate in direction to zero in C++

• A+
Category：Languages

I have some troubles explaining clearly but it's rather simple..

I have a double named value in my C++ program and I want to Floor it if it's a positive value and Ceil if it's a negative value, the precision is given by an external variable.

An example:

precision is of 1000 value is 0.2659 so approximated value is 0.265
value is -0.2659 so approximated value is -0.265

I have wrote a simple code but I was wondering if there was a more simple or/and way to do it.

Here what I have so far:

``void NodeImpl::approximation(double& value, const double& precision) {     if (value > 0.0)     {         value = std::floor(value * precision);     }     else     {         value = std::ceil(value * precision);     }     value /= precision; } ``

I have wrote a simple code but I was wondering if there was a more simple or/and way to do it.

You can use `std::trunc`:

``return std::trunc(value * precision) / precision; ``