我想用数学来做。圆的函数
当前回答
维基百科上有一个很好的四舍五入页面。
所有。net(托管)语言都可以使用任何公共语言运行时(CLR)舍入机制。例如,Math.Round()(如上所述)方法允许开发人员指定舍入的类型(舍入到偶数或远离零)。Convert.ToInt32()方法及其变体使用舍入到偶数。Ceiling()和Floor()方法是相关的。
您也可以使用自定义数字格式舍入。
注意Decimal.Round()使用了与Math.Round()不同的方法;
这是一篇关于银行家舍入算法的有用文章。 请看Raymond关于舍入的幽默帖子…
其他回答
这是为了在c#中四舍五入到小数点后2位:
label8.Text = valor_cuota .ToString("N2") ;
在VB。NET:
Imports System.Math
round(label8.text,2)
字符串a = "10.65678";
decimal d = Math.Round(Convert.ToDouble(a.ToString()),2)
如果你想四舍五入一个数字,你可以得到不同的结果,这取决于你如何使用Math.Round()函数(如果是四舍五入或四舍五入),你使用的是双精度数和/或浮点数,你应用的是中点四舍五入。特别是,当使用其中的操作或舍入变量来自操作时。比方说,你想把这两个数字相乘:0.75 * 0.95 = 0.7125。对吧?c#中没有
让我们看看如果你想四舍五入到小数点后第三位会发生什么:
double result = 0.75d * 0.95d; // result = 0.71249999999999991
double result = 0.75f * 0.95f; // result = 0.71249997615814209
result = Math.Round(result, 3, MidpointRounding.ToEven); // result = 0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = 0.712. Should be 0.713
如你所见,如果你想四舍五入到中点,第一个Round()是正确的。但是第二轮()是错误的,如果你想四舍五入。
这适用于负数:
double result = -0.75 * 0.95; //result = -0.71249999999999991
result = Math.Round(result, 3, MidpointRounding.ToEven); // result = -0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = -0.712. Should be -0.713
因此,恕我直言,您应该为Math.Round()创建自己的包装函数来满足您的需求。我创建了一个函数,其中参数'roundUp=true'表示舍入到下一个更大的数字。即:0.7125轮到0.713,-0.7125轮到-0.712(因为-0.712 > -0.713)。这是我创建的函数,适用于任何数量的小数:
double Redondea(double value, int precision, bool roundUp = true)
{
if ((decimal)value == 0.0m)
return 0.0;
double corrector = 1 / Math.Pow(10, precision + 2);
if ((decimal)value < 0.0m)
{
if (roundUp)
return Math.Round(value, precision, MidpointRounding.ToEven);
else
return Math.Round(value - corrector, precision, MidpointRounding.AwayFromZero);
}
else
{
if (roundUp)
return Math.Round(value + corrector, precision, MidpointRounding.AwayFromZero);
else
return Math.Round(value, precision, MidpointRounding.ToEven);
}
}
变量'corrector'用于修正浮点数或双精度数操作的不准确性。
你可能需要检查的一件事是数学的舍入机制。轮:
http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx
除此之外,我推荐数学。Round(inputnumber, numberOfPlaces)接近*100/100,因为它更干净。
下面是一些例子:
decimal a = 1.994444M;
Math.Round(a, 2); //returns 1.99
decimal b = 1.995555M;
Math.Round(b, 2); //returns 2.00
你可能还想看看银行家的四舍五入/四舍五入到偶数与以下过载:
Math.Round(a, 2, MidpointRounding.ToEven);
这里有更多的信息。
推荐文章
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 在单元测试中设置HttpContext.Current.Session
- 如何开始开发Internet Explorer扩展?
- 更新行,如果它存在,否则插入逻辑实体框架
- 在什么情况下SqlConnection会自动被征召到环境事务范围事务中?
- 用c#解析JSON
- Windows窗体中的标签的换行
- 为什么在c#中使用finally ?
- 为什么我不能在c#中有抽象静态方法?
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?
- 何时处理CancellationTokenSource?
- 如何获取正在执行的程序集版本?