您的位置:首页 > 编程语言 > C#

关于c#的四舍五入问题

2009-09-09 11:51 274 查看
下面是网上流传的关于c#的四舍五入的程序代码:

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

}

string strd = prestr + "." + poststr;

d = Double.Parse(strd);

return d;

}

关于这段代码其实是有Bug的。Bug的原因是当double的类型d是100.0时的时候。。也就是说正好小数点后面是0的情况下,那么d.ToString()得出来的结果是100....那么此时的strs数组的长度将为1。。。即string poststr = strs[1]; 这一句将会抛出数组越界的异常。因此要做如下简单的修改:

string str = value.ToString();
string[] strs = str.Split('.');
int idot = str.IndexOf('.');
if (idot > 0)
{
string prestr = strs[0];
string poststr = strs[1];
if (poststr.Length > decimals)
{
poststr = str.Substring(idot + 1, decimals);
}
string strd = prestr + "." + poststr;
value = Double.Parse(strd);
}
else
{
value = Double.Parse(str);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: