Fahad.ag
Fahad.ag

Reputation: 181

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?

Upvotes: 0

Views: 2523

Answers (5)

Nighil
Nighil

Reputation: 4129

if your string is static

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

else

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

Upvotes: 1

Paulie Waulie
Paulie Waulie

Reputation: 1690

    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.

Upvotes: 1

Alex
Alex

Reputation: 8116

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

This should work.

Upvotes: 1

Rob Levine
Rob Levine

Reputation: 41298

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);

Upvotes: 10

Random Dev
Random Dev

Reputation: 52270

you can try

int.Parse(myString.Replace(".", ""))

Upvotes: 3

Related Questions