string to number
How to convert a string to number 开发者_如何学Cin C#? What are the various ways.
Most of the numerical primitives have Parse and TryParse methods, I'd recommend using these. Parse will throw an exception if the format of the string being parsed is not recognised, whereas TryParse are fault tolerant.
int num = int.Parse("1");
int num = 0;
if (int.TryParse("1", out num)) {
// do something here.
You can also use Convert.ToInt32 etc....
static void Main(string[] args)
{
String textNumber = "1234";
int i = Int32.Parse(textNumber);
double d = Double.Parse(textNumber);
decimal d2 = Decimal.Parse(textNumber);
float f = float.Parse(textNumber);
}
Values in variables after execution of these commands:
textNumber = "1234"
i = 1234
d = 1234.0
d2 = 1234
f = 1234.0
Here are the various ways, and examples:
http://msdn.microsoft.com/en-us/library/bb397679.aspx
Int32.Parse Double.Parse Decimal.Parse
etc.
int myVar = int.Parse(string);
But with using Parse only you will need to have some form of exception handling if the passed string, isn't a number.
Thats why you should use TryParse
Then you can have
int nr;
if (int.TryParse(mystring, out nr) == false) {
//do something as converting failed
}
in C# you can convert a string to a number by:
Convert.ToUInt32("123");
Convert.ToInt64("678"); // to long
Convert.ToDouble("123");
Convert.ToSingle("146");
you can check this website for full detail : http://msdn.microsoft.com/en-us/library/bb397679.aspx
There is one thing to be aware of, when parsing decimal numbers:
The .NET framework will use the decimal number separators configured in Windows. For example here in Germany we write "1.129.889,12" which is "1,129,889.12" in the USA. Thus double.Parse(str) will behave differently.
You can however specify an IFormatProvider object as second parameter (this also applies to the ToString method). I'll make an example:
var ci = CultureInfo.InvariantCulture;
double a = double.Parse("98,89");
double b = double.Parse("98,89", ci);
Console.WriteLine(a.ToString(ci));
Console.WriteLine(b.ToString(ci));
The output on my computer is:
98.89
9889
So if you are for example reading configuration files, that use a number format independent of the interface language (which makes sense for configuration files), be sure to specify a proper IFormatProvider.
精彩评论