joao costa
joao costa

Reputation: 141

To get a specifc part of a numberin c#

I have a number:

Int64 a = 5021390010301;

And I want to get like

Int64 b = 30;

I tried:

string b = Convert.ToString(a).Substring(0 , 12);

That give me 502139001030. I also tried:

string b = Convert.ToString(a).Substring(11 , 12);

But that didn't work either.

Upvotes: 2

Views: 72

Answers (4)

Ivar
Ivar

Reputation: 6828

You can also solve it without converting it to a string first:

Int64 b = a % 1000 / 10;

This will work as long as you don't use a float or a double.

Upvotes: 1

chrsi
chrsi

Reputation: 1082

If you look at the Substring-Documentation at MSDN, you'll see that the second parameter is actually the length of the string.

If you want to get the last quarter of the string you have to write:

string b = convert.ToString(a).Substring(9 , 3);

And since you want an integer, you'll have to parse it:

int result = Int32.Parse(b);

Upvotes: 2

DavidG
DavidG

Reputation: 118937

The second parameter of string.Substring is the number of characters to take, not the index of the last character. So you will need something like this instead:

string b = Convert.ToString(a).Substring(10, 2);

Upvotes: 6

Tim Schmelter
Tim Schmelter

Reputation: 460098

The second argument of String.Substring is the length not the end index and the first index is 0.

int b = int.Parse(a.ToString().Substring(10, 2));

Upvotes: 1

Related Questions