开发者

C#, showing a numeric string as a number in original formatting

I need to write a simple method that gets a string as an input, checks if it's a number and shows the number in it's original formatting.

For example:

Input: Output:

"123"          123  
"-123"        -123  
"1.17"           1.17
"abd"          ERROR

I was thinking about int.parse and double.parse b开发者_运维百科ut is there anyway to check if the string representation is an int or double?

Thanks!!


You can use Decimal.TryParse() then just display the string if it is a number, or error if it isn't.


int.TryParse() and double.TryParse() will do the job for you.

The result of the parsing operation is stored in an out parameter see http://www.dotnetperls.com/int-tryparse

The double tryparse method works the same...


TryParse will handle it. http://msdn.microsoft.com/en-us/library/f02979c7.aspx

private static void TryToParse(string value)
   {
      int number;
      bool result = Int32.TryParse(value, out number);
      if (result)
      {
         Console.WriteLine("Converted '{0}' to {1}.", value, number);         
      }
      else
      {
         if (value == null) value = ""; 
         Console.WriteLine("Attempted conversion of '{0}' failed.", value);
      }
   }


        double result_double;
        int result_int;
        if (double.TryParse(your_string, out result_double))
            Console.WriteLine(result_double);
        else if (int.TryParse(your_string, out result_int))
            Console.WriteLine(result_int);
        else Console.WriteLine("error");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜