获取有效位数,当是小数时可以使用;
/// <summary> /// 小数获取有效位数 /// </summary> /// <param name="dvalue">数值</param> /// <param name="digit">位数</param> /// <returns>返回值</returns> public static double EffectiveValue(double dvalue, int digit) { if (dvalue == 0.0) return 0; if (dvalue > 1 || dvalue < -1) digit = digit - (int)Math.Log10(Math.Abs(dvalue)) - 1; else digit = digit + (int)Math.Log10(1.0 / Math.Abs(dvalue)); if (digit < 0) { dvalue = (int)(dvalue / Math.Pow(10, 0 - digit)) * Math.Pow(10, 0 - digit); digit = 0; } return Math.Round(dvalue, digit); }
获取到小数点后 digit 位有效数字
/// <summary> /// 获取有效位数 /// </summary> /// <param name="dvalue">数值</param> /// <param name="digit">位数</param> /// <returns>返回值</returns> public static decimal DoubleEffectiveValue(decimal dvalue, int digit) { decimal dint = decimal.Truncate(dvalue); decimal dxiaoshuo = dvalue - dint; //小数位 if (dxiaoshuo == 0) return dint; digit = digit + (int)Math.Log10(1.0 / Math.Abs(Convert.ToDouble(dxiaoshuo))); return decimal.Round(dvalue, digit); }