round() for float in C++

后端 未结 22 1180
时光取名叫无心
时光取名叫无心 2020-11-22 03:01

I need a simple floating point rounding function, thus:

double round(double);

round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1

I can find

22条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 03:34

    Boost offers a simple set of rounding functions.

    #include 
    
    double a = boost::math::round(1.5); // Yields 2.0
    int b = boost::math::iround(1.5); // Yields 2 as an integer
    

    For more information, see the Boost documentation.

    Edit: Since C++11, there are std::round, std::lround, and std::llround.

提交回复
热议问题