开发者

Casting using a decimal in C#

private int FindNumber(string sPar)
   {
      // Get the last number
      int len = sPar.Length;
      string s = sPar.Sub开发者_Python百科string(len-1);
      return new (int)Decimal(s);
   }

In this I am getting the error ; required . Can any ine help me on this.

Thank You!


Change your code to this:

private int FindNumber(string sPar)
{
      int len = sPar.Length;
      string s = sPar.Substring(len - 1);
      return Convert.ToInt32(s);
}

Or, even shorter:

private int FindNumber(string sPar)
{
      return Convert.ToInt32(sPar.Substring(sPar.Length - 1));
}


I'm not 100% what you are trying to do here, but if you want to get 4 as the result from the string "17894" i guess you want to write it like this with minimum number of changes:

private int FindNumber(string sPar) { 
  // Get the last number 
  int len = sPar.Length; 
  string s = sPar.Substring(len-1);
  return int.Parse(s); 
}

No reason to include a decimal and parse it to an int if you are only taking one char of the string anyway.

Note that this will give an exception if the last char of the string for any reason is not a number.


what is Decimal(s)? If you mean "parse as a decimal, then cast to int":

return (int)decimal.Parse(s);

If it is known to be an integer, just:

return int.Parse(s);

Actually, since you are only interested in the last digit, you could cheat:

private static int FindNumber(string sPar)
{
    char c = sPar[sPar.Length - 1];
    if (c >= '0' && c <= '9') return (int)(c - '0');
    throw new FormatException();
}


Decimal(s) is not a valid call since Decimal is a type. Try Decimal.Parse(s) instead if you are certain that s is a valid decimal, stored as a string. If not, use Decimal.TryParse instead.

Please take into account different Culture related problems also, check out the overload that takes an IFormatProvider (I think, not sure about the exact name)


Do you just want to parse the digit from the last position in the string?

private int FindNumber(string sPar)
{
    return int.Parse(sPar.Substring(sPar.Length - 1));
}

Note that this will fail if (a) the string is null, (b) the string is empty, or (c) the last character of the string isn't a digit. You should add some checking to your method if these situations are likely to be a problem.


The last line is completely wrong. Your code takes the last char of a string(that i presume is always a number) and cast it to an int.

Do the following

try{
return Int32.Parse(s);
}
catch(Exception e)
{
// manage conversion exception here
}


I suppose you want to convert string to decimal as your code is not very clear.

you can use

   Decimal d1;   
   if(Decimal.TryParse(sPar,out d1))    
   {
       return d1    
   }    
   else    
   {    
       return 0;    
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜