我想用数学来做。圆的函数
当前回答
public double RoundDown(double number, int decimalPlaces)
{
return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}
其他回答
这是为了在c#中四舍五入到小数点后2位:
label8.Text = valor_cuota .ToString("N2") ;
在VB。NET:
Imports System.Math
round(label8.text,2)
如果你想要一根绳子
> (1.7289).ToString("#.##")
"1.73"
或者小数
> Math.Round((Decimal)x, 2)
1.73m
但请记住!舍入不是分配的。圆(x*y) !=圆(x) *圆(y)。所以在计算结束之前不要做任何舍入运算,否则会失去精度。
我知道这是一个老问题,但请注意数学轮和字符串轮之间的以下区别:
decimal d1 = (decimal)1.125;
Math.Round(d1, 2).Dump(); // returns 1.12
d1.ToString("#.##").Dump(); // returns "1.13"
decimal d2 = (decimal)1.1251;
Math.Round(d2, 2).Dump(); // returns 1.13
d2.ToString("#.##").Dump(); // returns "1.13"
public double RoundDown(double number, int decimalPlaces)
{
return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}
如果你想四舍五入一个数字,你可以得到不同的结果,这取决于你如何使用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'用于修正浮点数或双精度数操作的不准确性。
推荐文章
- 何时使用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?
- 如何获取正在执行的程序集版本?