How to convert PI with precision of 15 digits to string in C++

3 Answers

0 votes
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
 
 
int main() {
    double pi = 3.14159265358979323846264338327950288419716939937510;
     
    std::ostringstream os;
    os << std::showpoint << std::setprecision(16) << pi;
    std::string str = os.str();
     
    std::cout << str;
}
 
 
 
 
/*
run:
 
3.141592653589793

*/

 



answered Nov 10, 2023 by avibootz
edited Nov 10, 2023 by avibootz
0 votes
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>


int main() {
    double pi = 3.14159265358979323846264338327950288419716939937510;
    
    std::ostringstream os;
    os << std::fixed << std::setprecision(15) << pi;
    std::string str = os.str();
    
    std::cout << str;
}




/*
run:

3.141592653589793

*/

 



answered Nov 10, 2023 by avibootz
edited Nov 10, 2023 by avibootz
0 votes
#include <iostream>
#include <charconv>
#include <array>

int main() {
    double pi = 3.14159265358979323846264338327950288419716939937510;

    std::array<char, 128> arr;
    
    auto [ptr, ec] = std::to_chars(arr.data(), arr.data() + arr.size(), pi, 
                                   std::chars_format::fixed, 15);

    std::string str(arr.data(), ptr);
     
    std::cout << str;
}
 
 
 
 
/*
run:
 
3.141592653589793

*/

 



answered Nov 10, 2023 by avibootz

Related questions

1 answer 134 views
1 answer 96 views
2 answers 182 views
1 answer 111 views
1 answer 129 views
3 answers 281 views
1 answer 183 views
...