Hello,

I need to convert manually string "6.812345678912345678912345678" to double (well, high-precision double i guess...).
Below is my code, which only converts the first 9 digits. After that it's all messed up. I really need to convert this long string to the same long number. How do I do this? Any suggestions will be very appreciated.


char inputstr[] = "6.8123456789123456789123456789";
double result1 = 0;

// part before the point
for(int i=0; i<1; i++)
{
result1 = (result1 * 10) + inputstr - '0';
}

double result2=0;
double temp;
int nDecimalDigits;
nDecimalDigits = 1;

//part after the point
for(int j=2; j<30; j++)
{
temp = inputstr[j] - '0';
nDecimalDigits *= 10;
temp /= nDecimalDigits;
result2 += temp;
}

Recommended Answers

All 5 Replies

You can use istringstream

#include <sstream>
#include <iostream>

int main()
{
    std::istringstream stm;
    double number;

    stm.str("6.8123456789123456789123456789");
    stm >> number;
    std::cout<<"Converted Value: "<<number;
    return 0;
}

You can even set the precision like this std::cout.precision(15);

But you can never achieve the oridinal number of digits even when you set the precision to something larger, such as 30. The most cout will display are 15 digits. Probably have to use some other math libraries, maybe boost, for that huge number of digits.

You are right, I just tried the code suggested above and it rounded it off to 15 digits. What is the best library out there to use for this purpose? I'll try Boost anyway, thank you very much!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.