Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 261
tony497 Avatar asked Oct 30 '18 10:10

tony497


1 Answers

You can use std::trunc:

return std::trunc(value * precision) / precision;
like image 178
eerorika Avatar answered Oct 12 '22 23:10

eerorika