在C#的Math类库中,四舍五入Round方法跟我们平常数学当中的不太一样,这个Round方法是直接去除小数部分,而没有取五进一,还有一个Ceiling方法,但这个方法是不管小数部分是哪个数字,都会进一,所以如果想使用四舍五入的话,也只能自己写个了。
以下是我自己写的一个四舍五入类,经过测试,小数位数不管有几位,都会按照咱们以前学过的方法后一位向前一位取五进一的,有不妥的地方,请大家指出来,如果大家谁有更好的方法,请帖出来,多谢!
正负数皆可
using System;
namespace Maths
{
public class Roundoff
{
/// <summary>
/// 四舍五入
/// </summary>
/// <param name="number">双精度数值</param>
/// <returns>四舍五入取整数值</returns>
public static int Round(double number)
{
int count = 0; //数组累加
string numstr = number.ToString(); //转换成字符串型
string[] numsplit = numstr.Split('.'); //将整数部分与小数部分分开
int resultValue = Int32.Parse(numsplit[0]);
int decimalValue = Int32.Parse(numsplit[1].Substring(0, 1));
int len = numsplit[1].Length; //小数部分的长度
//如果为1则直接运算
if (len == 1)
{
if (decimalValue >= 5)
{
resultValue += 1; //整数部分加1
}
}
else
{
//如果不大于4则不必进行四舍五入运行
if (decimalValue <= 3)
{
return resultValue;
}
else
{
int[] numarray = new int[len];
//将每个数字字符写入到数组中
foreach (char chars in numsplit[1])
{
numarray[count] = Int32.Parse(chars.ToString());
count++;
}
for (int i = len - 1; i > 0; i--)
{
//如果大于5则前一位加1
if (numarray[i] >= 5)
{
numarray[i - 1] += 1;
}
}
//如果第一个数字的值大于5则整数部分相加
if (numarray[0] >= 5)
{
resultValue += 1;
}
}
}
return resultValue;
}
}
}