c# - C#中如何四舍五入到任意数字?

标签 c# .net rounding

我正在用 C# 制作一个计算器,我想四舍五入到最接近的 1、10、100 等,也喜欢最接近的 0.1、0.001 等。我见过其他项目告诉我如何做但我尝试过,但似乎不起作用。

我已经尝试过:

textBox1.Text = Convert.ToString(Math.Round(Convert.ToDouble(Label1.Text), Convert.ToInt32(textBox1.Text), MidpointRounding.AwayFromZero));

还有...

textBox1.Text = Convert.ToString(Math.Round(Convert.ToDouble(Label1.Text), Convert.ToInt32(textBox1.Text)));

还有...

textBox1.Text = Convert.ToString(Convert.ToInt32(Label1.Text) / Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox1.Text));

最佳答案

Math.Round具有允许您四舍五入到特定小数的重载。

例如

Math.Round(0.05, 1, MidpointRounding.AwayFromZero);

结果为 0.1

如果您想四舍五入到最接近的 10、100 等,则需要进行更多数学运算。

Math.Round((double)50 / 100, MidpointRounding.AwayFromZero) * 100;

结果为 100,四舍五入到最接近的百位,而

Math.Round((double)55 / 10, MidpointRounding.AwayFromZero) * 10;

将为您提供最接近的 10,在本例中为 60。

关于c# - C#中如何四舍五入到任意数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53122756/

相关文章:

c# - 使用 EVOPdf 版本 6.10 将 Html 转换为 pdf

c# - 使用 BasicHttpBinding 进行 WCF 自定义证书验证

c# - 如何将时间四舍五入到最接近的 X 分钟?

c# - 如何在每第 n 个字符后拆分字符串?

c# - 为什么 Entity Framework 为 Azure 移动服务表 Controller 生成以下嵌套 SQL

C# 使用 newtonsoft 删除 json 子节点

c# - 坚持泛型和接口(interface)。需要基于代码的解决方案,可能需要重新设计接口(interface)

c# - 在没有 .NET 框架的情况下运行 .NET 应用程序

swift - 如何在 swift 中将 Double 舍入到最近的 Int?

java - BigDecimal 舍入问题