Kpt.Khaos
Kpt.Khaos

Reputation: 693

Simple way to split two numbers

My data reader reads the rows I want to split the result from the reader and take the second digit. So for example number is 42 I w want the 2. How can I accomplish this easily. There is about a million ways i have seen but none very simplistic. Thank you in advance!

 ld.ScaleGroup = (ScaleGroup)reader["ScaleGroup"];
 string[] split = ld.ScaleGroup.ToString().Split(?);

Upvotes: 0

Views: 166

Answers (2)

TypeIA
TypeIA

Reputation: 17250

You don't need to use Split() if you just want the 2nd character. Just write:

string str = ld.ScaleGroup.ToString();
char secondDigit = str[1];

Make sure str really has at least 2 characters, of course.

EDIT: If you want it as a string, see D Stanley's answer using Substring().

Split() is used for strings that consist of a sequence of tokens, separated by a delimiter character (or characters). For example, splitting "a,b,c" using the delimiter , would return an array of 3 strings "a", "b" and "c".

Upvotes: 3

D Stanley
D Stanley

Reputation: 152521

If you always want the second digit you can do

ld.ScaleGroup.ToString().Substring(1,1);

But what about numbers < 10? > 100?

Or if you always want the ones digit (e.g. 123 -> 3) then take the number mod 10:

int ones = ld.ScaleGroup % 10;

Upvotes: 7

Related Questions