龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > asp.net编程 >

ASP.NET中string,object,double转换为int类型心得

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
很多人使用Convert.ToInt32来强制转换,但发现当字符串值以小数,科学计数法表示时候无法转换。如果在ToInt32之前先将字符串转换为Detimal就不会有这种情况。 public static int Do( string valu

很多人使用Convert.ToInt32来强制转换,但发现当字符串值以小数,科学计数法表示时候无法转换。如果在ToInt32之前先将字符串转换为Detimal就不会有这种情况。

public static int Do(string value)
        {
            
if (string.IsNullOrEmpty(value)) return 0;

            
decimal result = 0;
            
try { decimal.TryParse(value, out result); }
            
catch { }
            
return System.Convert.ToInt32(result);
        }

我的转换类全部代码

namespace CS.Convert
{
    
public class toInt
    {
        
public static int Do(string value)
        {
            
if (string.IsNullOrEmpty(value)) return 0;

            
decimal result = 0;
            
try { decimal.TryParse(value, out result); }
            
catch { }
            
return System.Convert.ToInt32(result);
        }

        
public static int Do(decimal value)
        {
            
return System.Convert.ToInt32(value);
        }

        
public static int Do(float value)
        {
            
return System.Convert.ToInt32(value);
        }

        
public static int Do(double value)
        {
            
return System.Convert.ToInt32(value);
        }

        
public static int Do(int value)
        {
            
return value;
        }

        
public static int Do(object value)
        {
            
if (null == value || string.IsNullOrEmpty(value.ToString())) return 0;
            
decimal result = 0;
            
try { decimal.TryParse(value.ToString(), out result); }
            
catch { }
            
return System.Convert.ToInt32(result);
        }

        
public static int Do(DBNull value)
        {
            
return 0;
        }
    }
}

精彩图集

赞助商链接