I have a string that looks like this:
"0.4794255386042030002732879352156"
which is approximately the sin(0.5). I would like to format the string to look a much nicer
"4.794255386042e-1"
How can I achieve this? Remember I am dealing with strings and not numbers (float, double). Also I need to round to keep the number as accurate as possible, I can't just truncate. If I need to convert to a different data type I would prefer a long double because a regular double doesn't have enough precision. I'd like at least 12 decimal digits before rounding. Perhaps there is a simple sprintf() conversion I could do.
Something like this:
#include<iostream>
using namespace std;
int main()
{
        char *s = "0.4794255386042030002732879352156";
        double d;
        sscanf(s,"%lf",&d);
        printf("%.12e\n",d);
        return EXIT_SUCCESS;
}
Output:
# g++ a.cpp  && ./a.out
4.794255386042e-01
                        Are you looking for something like this?
Here is a sample:
 // modify basefield
#include <iostream>
#include <sstream>
using namespace std;
int main () {
    std::string numbers("0.4794255386042030002732879352156");
    std::stringstream stream;
    stream << numbers;
    double number_fmt;
    stream >> number_fmt;
    cout.precision(30);
    cout << number_fmt << endl;
    cout.precision(5);
    cout << scientific << number_fmt << endl;
  return 0;
}
Output:
0.479425538604203005377257795772
4.79426e-01
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With