★搜Asp.net★(www.soAsp.net),为专业技术文档网站。
包括Asp.net开发技术文档·C#开发技术文档·Access/SQL Server数据库开发技术文档·VB.NET开发技术文档。
还包括·项目实战经验总结·开发经验技巧总结·项目开发心得。


  
C#如何对计算结果四舍五放入

     本技巧主要介绍如何对计算结果四舍五放入。实现本技巧主要通Math类的Pow方法来实现的。运行程序,在文本框输入小数字,单击【确定按钮在四舍五入文框中数字。主要代码如下:

   public static double Round(double d, int i)
        {
            if (d >= 0)
            {
                d += 5 * Math.Pow(10, -(i + 1));//
            }
            else
            {
                d += -5 * Math.Pow(10, -(i + 1));
            }
            string str = d.ToString();
            string[] strs = str.Split('.');
            int idot = str.IndexOf('.');
            string prestr = strs[0];
            string poststr = strs[1];
            if (poststr.Length > i)
            {
                poststr = str.Substring(idot + 1, i);//截取需要位数
            }
            if (poststr.Length <= 2)
            {
                poststr = poststr + "0";
            }
            string strd = prestr + "." + poststr;
            d = Double.Parse(strd);//将字符串转换为双精度实数 
            return d;
        }
参数:
d表示要四舍五入的数;i表示要保留的小数点后为数