• 热门专题

C#判断字符串是否表示数值

作者:Programs Knowledge  发布日期:2012-11-29 11:39:40
Tag标签:字符串  
  • 下列范例显示如何使用 TryParse 与 long、byte 及 decimal 值的字符串表示。

    string numString = "1287543"; //"1287543.0" will return false for a long
    long number1 = 0;
    bool canConvert = long.TryParse(numString, out number1);
    if (canConvert == true)
      Console.WriteLine("number1 now = {0}", number1);
    else
      Console.WriteLine("numString is not a valid long");
    
    byte number2 = 0;
    numString = "255"; // A value of 256 will return false
    canConvert = byte.TryParse(numString, out number2);
    if (canConvert == true)
      Console.WriteLine("number2 now = {0}", number2);
    else
      Console.WriteLine("numString is not a valid byte");
    
    decimal number3 = 0;
    numString = "27.3"; //"27" is also a valid decimal
    canConvert = decimal.TryParse(numString, out number3);
    if (canConvert == true)
      Console.WriteLine("number3 now = {0}", number3);
    else
      Console.WriteLine("number3 is not a valid decimal");            

     

About IT165 - 广告服务 - 隐私声明 - 版权申明 - 免责条款 - 网站地图 - 网友投稿 - 联系方式
本站内容来自于互联网,仅供用于网络技术学习,学习中请遵循相关法律法规