我想用数学来做。圆的函数
当前回答
如果你想要一根绳子
> (1.7289).ToString("#.##")
"1.73"
或者小数
> Math.Round((Decimal)x, 2)
1.73m
但请记住!舍入不是分配的。圆(x*y) !=圆(x) *圆(y)。所以在计算结束之前不要做任何舍入运算,否则会失去精度。
其他回答
试试这个:
twoDec = Math.Round(val, 2)
//转换到小数点后两位
String.Format("{0:0.00}", 140.6767554); // "140.67"
String.Format("{0:0.00}", 140.1); // "140.10"
String.Format("{0:0.00}", 140); // "140.00"
Double d = 140.6767554;
Double dc = Math.Round((Double)d, 2); // 140.67
decimal d = 140.6767554M;
decimal dc = Math.Round(d, 2); // 140.67
= = = = = = = = =
// just two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"
也可以将“0”和“#”组合。
String.Format("{0:0.0#}", 123.4567) // "123.46"
String.Format("{0:0.0#}", 123.4) // "123.4"
String.Format("{0:0.0#}", 123.0) // "123.0"
public double RoundDown(double number, int decimalPlaces)
{
return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}
Math.Floor(123456.646 * 100) / 100 会返回123456.64吗
如果你想四舍五入一个数字,你可以得到不同的结果,这取决于你如何使用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?
- 如何获取正在执行的程序集版本?