推扬网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
推扬网 门户 经验分享 查看内容

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

2020-4-11 13:35| 发布者: admin| 查看: 537| 评论: 0

这篇文章主要介绍了C#四舍五入(函数)用法实例,有需要的朋友可以参考一下

效果:

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

事件:点击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())));
        }


鲜花

握手

雷人

路过

鸡蛋

最新评论

精选推荐

    广告服务|投稿要求|禁言标准|版权说明|免责声明|手机版|小黑屋|推扬网 ( 粤ICP备18134897号 )|网站地图 | 邮箱:vayae@hotmail.com

    GMT+8, 2025-6-9 21:08 , Processed in 0.293016 second(s), 28 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    返回顶部