Search code examples
c++boostprecisionboost-multiprecision

Boost C++ how to output all digits of float values without the exponent character?


    #include <iostream>
    #include <boost/multiprecision/cpp_dec_float.hpp>
    #include <boost/multiprecision/cpp_int.hpp>
    using boost::multiprecision::number;
    using boost::multiprecision::cpp_dec_float;
    using boost::multiprecision::cpp_dec_float_50;
    using boost::numeric_cast;
    using std::cout;


    int main()
    {
        srand(time(NULL));


        std::cout << std::setprecision(std::numeric_limits<cpp_dec_float_50>::digits10);
        cpp_dec_float_50 x = 0.0001;
        cpp_dec_float_50 y = x*x*x*x;
        std::cout << s << "\n";
    }

So I followed the documentation here: https://www.boost.org/doc/libs/1_63_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/cpp_dec_float.html

The output I expect to get is: 0.00000000000000000001 (20 zeros)

But the program's output is: enter image description here

For the question, I just want to remove the "e^-16" part. How can I do that? In addition, if someone else can help me to output that exact values, it'd also be very helpful.

Thank you.


Solution

  • You've instantiated x with a binary double value, which is not representable as a decimal. Here's how to fix that:

    #include <iostream>
    #include <boost/multiprecision/cpp_dec_float.hpp>
    
    using boost::multiprecision::cpp_dec_float_50;
    
    int main()
    {   
        std::cout << std::setprecision(std::numeric_limits<cpp_dec_float_50>::digits10);
        cpp_dec_float_50 x{"0.0001"};
        cpp_dec_float_50 y = x*x*x*x;
        std::cout << std::fixed;
        std::cout << y << "\n";
    }
    

    Output:

    0.00000000000000010000000000000000000000000000000000