Visual C++ .NET/Data Type/String to Number

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Convert Strings to Numbers

<source lang="csharp">

  1. include "stdafx.h"
  2. 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">

  1. 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">

  1. 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>