四舍六入五成双并保留一位有效位-数据修约
C#
/// <summary> /// 数据修约 -- 四舍六入5成双,至少保留一位有效位 /// 数值0.00512,保留2位,修约为0.01 /// </summary> /// <param name="modifyValue">原始数据</param> /// <param name="degit">保留位数</param> /// <returns></returns> public static string CalcValue(decimal modifyValue, int? degit) { decimal calValue = 0; int degitNotNull = degit ?? 2; calValue = Math.Round(modifyValue, degitNotNull); //按此修约为0则至少保留1位有效位数 if (calValue == 0 && modifyValue != 0) { return modifyValue.ToString("G1"); } else { return calValue.ToString("F" + degitNotNull); } }
/// <summary> /// 数据修约 -- 四舍六入5成双,至少保留一位有效位 /// 数值0.00512,保留2位,修约为0.005 /// </summary> /// <param name="modifyValue">原始数据</param> /// <param name="degit">保留位数</param> /// <returns></returns> public static string CalcValue2(decimal modifyValue, int? degit) { decimal calValue = 0; int degitNotNull = degit ?? 2; if (Math.Abs(modifyValue) >= 1) { calValue = Math.Round(modifyValue, degitNotNull); } //按此修约为0则至少保留1位有效位数 if (calValue == 0 && modifyValue != 0) { string value = modifyValue.ToString(); //从小数点后 value = value.Substring(value.IndexOf(".") + 1); for (int i = 0; i < value.Length; i++) { if ((i + 1) < degitNotNull) { calValue = Math.Round(modifyValue, degitNotNull); } else { calValue = Math.Round(modifyValue, (i + 1)); } } return calValue.ToString(); } else { return calValue.ToString("F" + degitNotNull); } }
SQL Server:
ROUND函数为四舍五入
/*四舍六入五成双*/ if object_id('fnRound') is not null drop function fnRound GO create function fnRound(@num float,@i int) returns varchar(20) as begin declare @str varchar(20) /*转换成字符类型*/ declare @str2 varchar(20) /*小数位数后面的字符串*/ declare @str3 varchar(2) /*小数位数字符串*/ set @str = convert(varchar,@num) if (charindex('.',reverse(@str)) <= 0) begin if @i > 0 begin set @str = @str + '.' while @i > 0 begin set @str = @str + '0' set @i = @i - 1 end end return @str end set @str2 = reverse(substring(reverse(@str),1,charindex('.',reverse(@str)) - 1 - @i)) set @str3 = substring(@str,charindex('.',@str) + 1,@i) if @str2%5 = 0 and @str3%2 = 0 /*如果符合"五成双"*/ set @str = substring(@str,1,charindex('.',@str) + @i) else /*否则四舍五入*/ set @str = convert(varchar,round(@num,@i)) RETURN @str end GO