#region 修约函数
/// </summary>
/// <param name="data_val">输入数值</param>
/// <param name="len">保留几位小数</param>
/// <returns></returns>
public static decimal round_gbt8170(decimal data_val,int len)
{
string num = data_val.ToString();
string zs = num.Split('.')[0];//整数
string xs = "";
if(num.Split('.').Length>0)
xs = num.Split('.')[1];//小数数
if (len>= xs.Length)//小数位数<=需要保留几位小数
{
xs = xs.ToString().PadRight(len, '0');
}
else
{
string lxs = "";
if(len>1)
lxs = xs.Substring(0, len - 1);
int ds = Convert.ToInt32(xs.Substring(len - 1, 1));//取保留小数位数的数字
int ns =Convert.ToInt32(xs.Substring(len , 1));//取保留小数位数的下一位数字
if (ns < 5)//舍去
{
xs = lxs + ds.ToString();
}
else if (ns >5)//进1
{
xs = lxs + (ds+1).ToString();
}
else if (ns ==5)
{
string hs = "";//取保留小数位数的下一位数字的后面所有数字
if (xs.Length - 1 > len)
hs = xs.Substring(len + 1);
if (hs != "" && Convert.ToInt32(hs) > 0) //舍弃数字的最左一位数字是 5,且其后有非0数字时进一,即保留数字的末位数字加1
xs = lxs + (ds + 1).ToString();
else //拟舍弃数字的最左一位数字为5,且其后无数字或皆为0时,若所保留的末位数字为奇数(1,3,5,7,9)则进一,即保留数字的末位数字加1;若所保留的末位数字为偶数(0,2,4,6,8),则舍去。
{
if(ds%2==0) //所保留的末位数字为偶数(0, 2, 4, 6, 8),则舍去
{
xs = lxs + ds.ToString();
}
else if (ds % 2 ==1) //,若所保留的末位数字为奇数(1,3,5,7,9)则进一,即保留数字的末位数字加1
{
xs = lxs + ds.ToString();
xs = lxs + (ds + 1).ToString();
}
}
}
}
decimal fh = data_val;
if (len > 0)
fh = Convert.ToDecimal(zs + "." + xs);
else
fh = Convert.ToDecimal(zs);
return fh;
}
#endregion