开发者

using numbers in a string

开发者 https://www.devze.com 2022-12-18 04:58 出处:网络
Can I use number开发者_开发问答s while using String data type?Sure you can, and if you want to use them as numbers you can parse the string. E.g. for an integer:

Can I use number开发者_开发问答s while using String data type?


Sure you can, and if you want to use them as numbers you can parse the string. E.g. for an integer:

string numberAsString = "42";
int numberFromString;
if (int.TryParse(numberAsString, out numberFromString))
{
    // number successfully parsed from string
}

TryParse will return a bool telling if the parsing were successful. You can also parse directly if you know the string contains a number - using Parse. This will throw if the string can't be parsed.

int number = int.Parse("42"); 


You can have numbers in a string.

string s = "123";

..but + will concatenate strings:

string s = "123";
string other = "4";
Debug.Assert(s + other != "127");
Debug.Assert(s + other == "1234");


Numbers can be easily represented in a string:

string str = "10";
string str = "01";

string str = 9.ToString();

However, these are strings and cannot be used as numbers directly, you can't use arithmetic operations on them and expect it to work:

"10" + "10"; // Becomes "1010"
"10" / "10"; // Will not compile


You can easily store numbers as a string:

string foo = "123";

but that only helps you if you actually want numbers in a string. For arithmetic purposes, use a number. If you need to display that later, us a format string.


String number1 = "123456";

keep in mind. using that number for arithmatic purpose, you have to convert that string into proper type like

int number1Converted = Int32.Parse(number1);    
int.TryParse(number1 , out number1Converted );

for double

double doubleResult = 0.0;
double.TryParse("123.00", out doubleResult);
0

精彩评论

暂无评论...
验证码 换一张
取 消