IsNumieric Function in C# – To use in Excel..

Excel is a peculiar one.  If  you have any numbers or text like 32E22, it takes to exponent form.  But there are so many logics by which it can be done.  In C# one famous method is to have try & catch and by calling converting function, throw error.  This is unethical method.  You should not throw exception to proceed with your logic.  So, I wrote the following code to capture that.  Simple & straight forward.

strToCheck – String that needs to be checked.
boolDecimalConsideration – Whether period (.) has to be considered for validating  

public static bool IsNumeric(string strToCheck, bool boolDecimalConsideration){

if(strToCheck == “”)return false;

char [] chArr = strToCheck.ToCharArray();char [] chSeperator = {‘E’};

bool boolRetVal = true;if(strToCheck.IndexOf(“E”) > 0){

string [] strArr = strToCheck.Split(chSeperator);

if (strArr.Length > 2)boolRetVal = false;

if (boolRetVal == true && IsNumeric(strArr[0], true) && IsNumeric(strArr[1], false))boolRetVal = true;else

boolRetVal = false;return boolRetVal;}

for(int i=0; i<chArr.Length && boolRetVal; i++){

char ch = chArr[i];

int it = (int)ch;if( boolDecimalConsideration && ch == ‘.’)

continue;else if( (it >= 48 && it <= 57) )

continue;else

boolRetVal = false;}

return boolRetVal;}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.