欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C#四舍五入(函数)用法实例

时间:2021-06-17 09:17:57|栏目:.NET代码|点击:

效果:

说明:输入小数,然后输入要保留的位数,

事件:点击Button

代码:

复制代码 代码如下:

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;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox3.Text=Convert.ToString(Math.Round(Convert.ToDouble(textBox1.Text.Trim()),Convert.ToInt16(textBox2.Text.Trim())));
        }

上一篇:在c#中使用servicestackredis操作redis的实例代码

栏    目:.NET代码

下一篇:.net 应对网站访问压力的方案总结

本文标题:C#四舍五入(函数)用法实例

本文地址:http://www.codeinn.net/misctech/143399.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有