简体   繁体   中英

C# - converting string with decimals to integer

I have a string "1.0.0.1";

I want to convert this string to numeric values = 1001;

how do i do this?

The easiest way would be to strip out the periods and parse:

var input = "1.0.0.1";
int number = int.Parse(input.Replace(".", ""));

Note - this version will throw an exception if the string is not a number once the periods are stripped out. If you don't want this behaviour, you can use int.TryParse

var input = "1.0.0.1";
int number;

int.TryParse(input.Replace(".", ""), out number);

你可以试试

int.Parse(myString.Replace(".", ""))
    Int32 num;
    String numString = "1.0.0.1";

    Boolean success = Int32.TryParse(numString.Replace(".",""), out num);

Then you can test that success is true before attempting to use the num integer.

        string number = "1.0.1.0.1";
        var convertedString = int.Parse(number.Replace(".",""));

This should work.

if your string is static

 int number = Convert.ToInt32("1.0.0.1".Replace(".", ""));

else

int number = Convert.ToInt32(yourstringvariable.Replace(".", ""));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM