Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string into scientific notation

Tags:

c++

string

math

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.

like image 348
John Scipione Avatar asked Dec 29 '09 19:12

John Scipione


2 Answers

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
like image 182
codaddict Avatar answered Sep 21 '22 15:09

codaddict


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

like image 34
coelhudo Avatar answered Sep 21 '22 15:09

coelhudo