Visual C++ .NET/Data Type/String to Number
Convert Strings to Numbers
<source lang="csharp">
- include "stdafx.h"
- using <mscorlib.dll>
using namespace System; int main(void) {
int a = Int32::Parse("123"); int b = Int32::Parse("$547,295.00"); double c = Double::Parse("123.456"); double d = Double::Parse("5.743955e+005"); Console::WriteLine(a); Console::WriteLine(b); Console::WriteLine(c); Console::WriteLine(d); return 0;
}
</source>
Convert String to decimal
<source lang="csharp">
- include "stdafx.h"
using namespace System; void main() {
Decimal w = System::Convert::ToDecimal("123456789012345678901.2345678"); Console::WriteLine( w );
}
</source>
parse the string to get the integer value
<source lang="csharp">
- include "stdafx.h"
using namespace System; int main() {
String^ str1 = "115"; String^ str2 = "1.4e-12"; int i = Int32::Parse( str1 );
double x = Double::Parse( str2 ); // int j = Convert::ToInt32( str1 ); double y = Convert::ToDouble( str2 ); try { int k = Int32::Parse("bad format"); } catch(FormatException^ e) { Console::WriteLine("Exception occurred! {0}", e->Message ); }
}
</source>