Search code examples
c++floating-point

How to print all the decimals of a float 128 to the console


I wanted to print the constant e, but I quickly came to realize, that cout cannot handle the __float128. Seeing as __float128 cannot be printed, by the function. I also tried some solutions, available on the web, and all of them told me to convert it to a double. but that would lose the precision of the calculation.

I am using GCC x64.

the code:

        #include <iostream>
        #include <stdlib.h>
        #include <iomanip>
        #include <quadmath.h>
        #include <format>
        #include <charconv>

        volatile __float128 fact(unsigned int n)
        {
            long int fac=1;
            for (int x=n;x>1;x--){
            fac *=x;
            }
            return fac;
        }



        int main(){
        volatile __float128 e=0.0;
        for (int x =0;x<10000;x++){
        e +=1/fact(x);
        }
        std::cout<<e;
        }

As you can see, it does not print.


Solution

  • C++23 changed to_chars API to:

    std::to_chars - cppreference.com

    std::to_chars_result  
        to_chars( char* first, char* last, /* floating-point-type */ value,  
                  std::chars_format fmt, int precision );
    

    (since C++23)

    So looks like there is a way.

        __float128 x = 1.123456789012345678901l;
        char buffer[256];
        std::to_chars(std::begin(buffer), std::end(buffer), x);
        std::cout << buffer;
    

    https://godbolt.org/z/sKdKxYKdG

    But first I would test this fairly before using.

    Also check if there are other changes which could use address this in alternative way. std::format/std::print should do it nicely too: https://godbolt.org/z/aMzfGM5vx