欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-22 14:37:28
效果: 说明:输入小数,然后输入要保留的位数, 事件:点击button 代码:复制代码 代码如下:public static double round(doubl...

效果:

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