开发者

Round the nearest number

开发者 https://www.devze.com 2023-02-15 21:42 出处:网络
开发者_如何学PythonI tried everything from round the nearest code. It is not the code that I\'m looking for.

开发者_如何学PythonI tried everything from round the nearest code. It is not the code that I'm looking for. I tried round the nearest number 0.00750 to this 0.0080 How do around before decimal?

I want something like this:

0.0089 => 0.0090
0.0021 => 0.0020
0.1022 => 0.1020


math.h contains double round(double) which will address the rounding part. To round to some number of decimal places try something like:

double roundPlaces(double d, int places)
{
   double factor = pow(10, places); // pow also in math.h

   return round(d * factor) / factor;
}

and then for your examples roundPlaces(0.0089, 3) produces 0.009.


you can make your own function using standard C function...

There's no round() in the C++ std library. You can write one yourself though:

double round(double d)
{
  return floor(d + 0.5);
}

(you can use C function in objective C )

0

精彩评论

暂无评论...
验证码 换一张
取 消