I am trying to convert the std::string Number3 = "0.31" to a double in the code below.
I have used a MessageBox to show the result.
What happens is that double Convert is returning the value of: 0
What I have discovered is that if I instead would have written Number3 = "1.31",
Convert would have returned: 1
So it seems that the decimals is dissapearing in the conversion.

What could I be doing wrong here ?

stringstream Number1;
std::string Number2;
std::string Number3 = "0.31";

double Convert = atoi(Number3.c_str());

Number1 << Convert;
Number2 = Number1.str();

String^ NumberNew = gcnew String(Number2.c_str());

MessageBox::Show(NumberNew);

Recommended Answers

All 4 Replies

So it seems that the decimals is dissapearing in the conversion.

atoi() converts a character string to an integer meaning that no decimal points are available. The stringstream is capable of doing the conversion, so you don't need to use any of the C-library conversion routines.

std::string Number3 = "0.31";
stringstream Number1(Number3);
double Convert;
Number1 >> Convert;
String^ NumberNew = gcnew String(Number1.str());
MessageBox::Show(NumberNew);

Thank you. This was what I thought too, that atoi was converting to an integer.
I have tried to compile the code that I received and the compilation was not
successful for this line. I wonder if this line is correct.
I receive this message:
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

String^ NumberNew = gcnew String(Number1.str());

atoi() converts a character string to an integer meaning that no decimal points are available. The stringstream is capable of doing the conversion, so you don't need to use any of the C-library conversion routines.

std::string Number3 = "0.31";
stringstream Number1(Number3);
double Convert;
Number1 >> Convert;
String^ NumberNew = gcnew String(Number1.str());
MessageBox::Show(NumberNew);

Sorry, it should be String^ NumberNew = gcnew String(Number1.str().[B]c_str()[/B]); stringstream::str() returns a std::string, hence that c_str() is needed there.

Okay, then I understand. This did work great.

Thanks...

Sorry, it should be String^ NumberNew = gcnew String(Number1.str().[B]c_str()[/B]); stringstream::str() returns a std::string, hence that c_str() is needed there.

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.