Get a rounded value of a non-integer in compile time ?

How to compute the rounded value of a non-integer i.e. float/double value in compile time ?
In the best way as usually, as a function form e.g. constexpr fn(double n) {}
Last edited on
As usual, implementing correct algorithms for floating point numbers requires some amount of specialized knowledge. Fortunately, libstdc++'s implementation of std::round is constexpr via library extension. Use it if possible.

Otherwise, if wrong behavior is acceptable at boundary conditions, you may be able to approximate round-half-up with code like
1
2
3
4
constexpr double approx_round(double x) 
{ 
  return static_cast<std::uint_least64_t>(x + 0.5); 
}
This may be sufficient for some applications.
Last edited on
Topic archived. No new replies allowed.