c++boostrational-number

boost rational cast to double


Using the following bit of code compiled against boost 1.62:

#include <boost/rational.hpp>
#include <iostream>

int main() {
    auto val = boost::rational<int64_t>(499999, 2);
    std::cout << val << std::endl;
    std::cout << boost::rational_cast<double>(val) << std::endl;
}

I get the following output:

499999/2
250000

I would expect rational_cast to output 249999.5 Can anyone explain what I am doing wrong?


Solution

  • Modify the default formatting for floating-point input/output: std::cout << std::fixed << boost::rational_cast<double>(v) << std::endl; add std::fixed to it.