using System; using System.Collections.Generic; using System.Text; namespace APT.Infrastructure.Core { public static class LibUtils { /// /// 转为字符串 /// /// /// public static string ToString(object obj) { if (obj == null||obj==DBNull.Value) return string.Empty; return obj.ToString(); } /// /// 转为整数 /// /// /// public static int ToInt(object obj) { if (obj == null || obj == DBNull.Value) return 0; try { return Convert.ToInt32(obj.ToString()); } catch { } return 0; } /// /// 转为Decimal /// /// /// public static decimal ToDecimal(object obj) { if (obj == null || obj == DBNull.Value) return 0; try { return Convert.ToDecimal(obj.ToString()); } catch { } return 0; } /// /// 转为日期 /// /// /// public static DateTime? ToDateTime(object obj) { if (obj == null || obj == DBNull.Value) return null; try { return Convert.ToDateTime(obj.ToString()); } catch { } return null; } /// /// 转为Guid /// /// /// public static Guid? ToGuid(object obj) { if (obj == null || obj == DBNull.Value) return null; try { return new Guid(obj.ToString()); } catch { } return null; } /// /// 转为布尔类型 /// /// /// public static bool ToBoolean(object obj) { if (obj == null || obj == DBNull.Value) return false; try { return Convert.ToBoolean(obj); } catch { string str = LibUtils.ToString(obj); if (string.Compare(str, "是", true) == 0) return true; } return false; } /// /// 比较两个指定的 System.String 对象(其中忽略或考虑其大小写),并返回一个整数 /// /// /// /// 是否忽略大小写 /// public static int Compare(object objA, object objB, bool ignoreCase = true) { if (objA == null || objB == null) return 0; return string.Compare(ToString(objA), ToString(objB), ignoreCase); } /// /// 保留指定小数点位数 /// /// /// /// /// public static decimal Round(decimal qty,int len, LibRoundTypeEnum type) { if (type == LibRoundTypeEnum.向上进位) { if (len != 0) { var s = qty.ToString().Split('.'); if (s.Length >= 2) { var x = s[1].PadRight(6, '0'); qty = Convert.ToDecimal(s[0] + "." + x.Substring(0, len)); } } else qty = Math.Ceiling(qty); return qty; } else if (type == LibRoundTypeEnum.向下舍弃) { if (len != 0) { var s = qty.ToString().Split('.'); if (s.Length >= 2) { var x = s[1].PadRight(6, '0'); qty = Convert.ToDecimal(s[0] + "." + x.Substring(0, len)); if (x[len] != '0') qty += 1 / (decimal)Math.Pow(10, len); } } else { qty = Math.Floor(qty); } return qty; } return Math.Round(qty, len, MidpointRounding.AwayFromZero); } } }