round() for float in C++

后端 未结 22 1218
时光取名叫无心
时光取名叫无心 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条回答
  •  鱼传尺愫
    2020-11-22 03:19

    A certain type of rounding is also implemented in Boost:

    #include 
    
    #include 
    
    template T round2(const S& x) {
      typedef boost::numeric::conversion_traits Traits;
      typedef boost::numeric::def_overflow_handler OverflowHandler;
      typedef boost::numeric::RoundEven Rounder;
      typedef boost::numeric::converter Converter;
      return Converter::convert(x);
    }
    
    int main() {
      std::cout << round2(0.1) << ' ' << round2(-0.1) << ' ' << round2(-0.9) << std::endl;
    }
    

    Note that this works only if you do a to-integer conversion.

提交回复
热议问题