C开发经验技巧宝典

时间:2022-11-20 20:46:26 作者:壹号 字数:875字

5.1 数字处理技巧

本实例主要介绍如何对计算结果四舍五入。本实例主要是通过Math类的Pow方法来实现的。运行程序,在文本框中输入数字,单击“确定”按钮四舍五入文本框中的数字。主要代码如下:

…… 此处隐藏0字 ……

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