当前位置: 移动技术网 > IT编程>开发语言>c# > C#四舍五入(函数)用法实例

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

效果:

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

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网