效果:
说明:输入小数,然后输入要保留的位数,
事件:点击Button
代码:
1 public static double Round(double d, int i) 2 { 3 if (d >= 0) 4 { 5 d += 5 * Math.Pow(10, -(i + 1));//求指定次数的指定次幂 6 } 7 else 8 { 9 d += 5 * Math.Pow(10, -(i + 1)); 10 } 11 string str = d.ToString(); 12 string[] strs = str.Split('.'); 13 int idot = str.IndexOf('.'); 14 string prestr = strs[0]; 15 string poststr = strs[1]; 16 if (poststr.Length > i) 17 { 18 poststr = str.Substring(idot + 1, i);//截取需要位数 19 } 20 if (poststr.Length <= 2) 21 { 22 poststr = poststr + "0"; 23 } 24 string strd = prestr + "." + poststr; 25 d = double.Parse(strd);//将字符串转换为双精度实数 26 return d; 27 } 28 29 private void button1_Click(object sender, EventArgs e) 30 { 31 textBox3.Text=Convert.ToString(Math.Round(Convert.ToDouble(textBox1.Text.Trim()),Convert.ToInt16(textBox2.Text.Trim()))); 32 }