跳至页脚内容
.NET 帮助

Math.Round C#(开发人员如何使用)

在 C# 编程领域,Math.Round 值方法在数值四舍五入方面发挥着举足轻重的作用,尤其是在处理双值和小数数据类型时。该方法允许开发人员将给定的数值四舍五入到最接近的整数值或指定的小数位数,从而为数学运算提供灵活性和精确性。 有几种四舍五入类型可供选择,例如中点四舍五入。 在本文中,我们将深入探讨 C# 中 Math.Round 的复杂性,探索其各个方面和使用场景。 在本文的后续章节中,我们将探讨利用 Iron SoftwareIronPDF 库来处理 PDF。

C# 中 Math.Round 的基础知识;

Math.Round 方法

C# 中的 Math.Round 方法是一种功能强大的工具,用于使用指定的四舍五入约定对小数位数进行四舍五入。 它是 System 命名空间的一部分,提供多个重载以适应不同的舍入操作。

// Methods overloaded by Math.Round
Math.Round(Double)
Math.Round(Double, Int32) // Int32 specifies number of fractional digits
Math.Round(Double, Int32, MidpointRounding)  // Int32 specifies number of fractional digits, MidpointRounding is the type of rounding method
Math.Round(Double, MidpointRounding)  // MidpointRounding is the type of rounding method
Math.Round(Decimal)
Math.Round(Decimal, Int32) // Int32 specifies number of fractional digits
Math.Round(Decimal, Int32, MidpointRounding)
Math.Round(Decimal, MidpointRounding)
// Methods overloaded by Math.Round
Math.Round(Double)
Math.Round(Double, Int32) // Int32 specifies number of fractional digits
Math.Round(Double, Int32, MidpointRounding)  // Int32 specifies number of fractional digits, MidpointRounding is the type of rounding method
Math.Round(Double, MidpointRounding)  // MidpointRounding is the type of rounding method
Math.Round(Decimal)
Math.Round(Decimal, Int32) // Int32 specifies number of fractional digits
Math.Round(Decimal, Int32, MidpointRounding)
Math.Round(Decimal, MidpointRounding)
$vbLabelText   $csharpLabel

双倍值滚圆

在处理双数值时,Math.Round 通常用于将数字四舍五入到最接近的整数。 例如:

double originalValue = 3.75;
double roundedValue = Math.Round(originalValue); 
// Output: 4
double originalValue = 3.75;
double roundedValue = Math.Round(originalValue); 
// Output: 4
$vbLabelText   $csharpLabel

在本例中,Math.Round 方法将原始双数值 3.75 四舍五入为最接近的整数值,即 4。

小数点舍入

同样,Math.Round 方法适用于十进制值。 请考虑以下示例:

decimal originalValue = 8.625m;
decimal roundedValue = Math.Round(originalValue, 2);
// Output: 8.63
decimal originalValue = 8.625m;
decimal roundedValue = Math.Round(originalValue, 2);
// Output: 8.63
$vbLabelText   $csharpLabel

此处使用 Math.Round 方法将小数 8.625 四舍五入到小数点后两位,得到四舍五入后的数值 8.63。

最近整数值

Math.Round 的主要用途是将给定数值四舍五入为最接近的整数。 当小数部分正好位于两个整数的中间时,该方法遵循指定的四舍五入惯例。 MidpointRounding 枚举可用作 Math.Round 方法的参数,并决定是向最接近的偶数舍入还是从零开始舍入。

指定的四舍五入规则

让我们来探讨一下如何使用 MidpointRounding 模式:

double originalValue = 5.5;
double roundedValueEven = Math.Round(originalValue, MidpointRounding.ToEven);
double roundedValueOdd = Math.Round(originalValue, MidpointRounding.AwayFromZero);
// Output: roundedValueEven = 6, roundedValueOdd = 6
double originalValue = 5.5;
double roundedValueEven = Math.Round(originalValue, MidpointRounding.ToEven);
double roundedValueOdd = Math.Round(originalValue, MidpointRounding.AwayFromZero);
// Output: roundedValueEven = 6, roundedValueOdd = 6
$vbLabelText   $csharpLabel

在本例中,当对数值 5.5 进行四舍五入时,MidpointRounding.ToEven 向最接近的偶数取整(结果为 6),而 MidpointRounding.AwayFromZero 从零开始取整,结果为 6。

舍入到指定的小数位数

要将一个数字四舍五入到指定的小数位数,Math.Round 方法允许包含一个代表小数位数的附加参数:

decimal originalValue = 9.123456m;
decimal roundedValue = Math.Round(originalValue, 3); 
// Output: 9.123
decimal originalValue = 9.123456m;
decimal roundedValue = Math.Round(originalValue, 3); 
// Output: 9.123
$vbLabelText   $csharpLabel

这里,小数点后的数字 9.123456 被四舍五入到小数点后三位,得到四舍五入后的数值 9.123。

C# 中点值和四舍五入约定;

当结果中最小有效数字后的数值正好位于两个数字的中间时,就产生了中点值。 例如,当四舍五入到小数点后两位 2.57 时,2.56500 是一个中点值;当四舍五入到整数 4 时,3.500 是一个中点值。在没有定义四舍五入惯例的情况下,如何在中点值的四舍五入策略中识别最接近的值是一个难题。

C# 中的 Round 方法支持两种处理中点值的四舍五入约定:

  • 从零开始四舍五入:中点值会四舍五入到从零开始的下一个数字。 该方法由 MidpointRounding.AwayFromZero 枚举成员表示。

  • 四舍五入到最接近的偶数(银行四舍五入):中点值四舍五入为最接近的偶数。 这种四舍五入方法由 MidpointRounding.ToEven 枚举成员表示。
decimal[] decimalSampleValues = { 1.15m, 1.25m, 1.35m, 1.45m, 1.55m, 1.65m };
decimal sum = 0;

// Calculate true mean values.
foreach (var value in decimalSampleValues)
{ 
    sum += value; 
}
Console.WriteLine("True mean values: {0:N2}", sum / decimalSampleValues.Length);

// Calculate mean values with rounding away from zero.
sum = 0;
foreach (var value in decimalSampleValues)
{ 
    sum += Math.Round(value, 1, MidpointRounding.AwayFromZero); 
}
Console.WriteLine("AwayFromZero mean: {0:N2}", sum / decimalSampleValues.Length);

// Calculate mean values with rounding to the nearest even.
sum = 0;
foreach (var value in decimalSampleValues)
{ 
    sum += Math.Round(value, 1, MidpointRounding.ToEven); 
}
Console.WriteLine("ToEven mean: {0:N2}", sum / decimalSampleValues.Length);
decimal[] decimalSampleValues = { 1.15m, 1.25m, 1.35m, 1.45m, 1.55m, 1.65m };
decimal sum = 0;

// Calculate true mean values.
foreach (var value in decimalSampleValues)
{ 
    sum += value; 
}
Console.WriteLine("True mean values: {0:N2}", sum / decimalSampleValues.Length);

// Calculate mean values with rounding away from zero.
sum = 0;
foreach (var value in decimalSampleValues)
{ 
    sum += Math.Round(value, 1, MidpointRounding.AwayFromZero); 
}
Console.WriteLine("AwayFromZero mean: {0:N2}", sum / decimalSampleValues.Length);

// Calculate mean values with rounding to the nearest even.
sum = 0;
foreach (var value in decimalSampleValues)
{ 
    sum += Math.Round(value, 1, MidpointRounding.ToEven); 
}
Console.WriteLine("ToEven mean: {0:N2}", sum / decimalSampleValues.Length);
$vbLabelText   $csharpLabel

输出

!a href="/static-assets/pdf/blog/math-round-csharp/math-round-csharp-1.webp">Math.Round C#(如何为开发人员工作):图 1 - 双精度浮点输出。

MidpointRounding 模式

!a href="/static-assets/pdf/blog/math-round-csharp/math-round-csharp-2.webp">Math.Round C#(如何为开发人员工作):图 2 - 中点舍入。

AwayFromZero:1

AwayFromZero 四舍五入策略将一个数字四舍五入到最接近的数字,将一个数字从零四舍五入到其他两个数字的中间。

ToZero: 2

该策略的特点是直接四舍五入为零。 翻译结果应最接近无限精确的结果,且在量级上不得高于无限精确的结果。

ToEven: 0

这种策略包括四舍五入,当一个数字位于两个数字的中间时,就四舍五入到最接近的偶数。

ToNegativeInfinity:3

这一策略要求向下取整,结果应最接近无限精确的结果,但不得大于无限精确的结果。

ToPositiveInfinity:4

这种策略包括向上取整,结果应最接近且不小于无限精确的结果。

精度和双精度浮点运算

精度和双数值

在使用双精度浮点数时,必须了解浮点表示法的性质可能导致的不精确性。 Math.Round 方法可将数值四舍五入到最接近的整数或指定的小数位数,从而帮助减轻精度问题。

使用 Math.Round 指定精度

开发人员可以利用 Math.Round 方法实现所需的计算精度:

double originalValue = 123.456789;
double result = Math.Round(originalValue, 4);
// Output: 123.4568, rounded value
double originalValue = 123.456789;
double result = Math.Round(originalValue, 4);
// Output: 123.4568, rounded value
$vbLabelText   $csharpLabel

在本例中,双数值 123.456789 四舍五入到小数点后四位,得到更精确的数值 123.4568。

中点舍入策略

处理中点值

当一个分数值正好位于两个整数的中间时,中点舍入策略就变得至关重要。 Math.Round 方法采用指定的 MidpointRounding 策略来解决此类情况。

中点舍入示例

下面是一个使用中点四舍五入的例子:

double originalValue = 7.5;
double roundedValue = Math.Round(originalValue, MidpointRounding.AwayFromZero);
// Output: 8
double originalValue = 7.5;
double roundedValue = Math.Round(originalValue, MidpointRounding.AwayFromZero);
// Output: 8
$vbLabelText   $csharpLabel

这里,数值 7.5 从 0 舍入,得到四舍五入后的数值 8。

在现实世界中的应用

以下是一些在不同语境中的应用实例:

财务计算

在金融应用中,精确的四舍五入至关重要。 例如,在计算利率、转换货币或处理税收计算时,可以使用 Math.Round 方法来确保结果四舍五入到适当的小数位数,以符合财务标准。

double interestRate = 0.04567;
double roundedInterest = Math.Round(interestRate, 4); // Round to 4 decimal places
double interestRate = 0.04567;
double roundedInterest = Math.Round(interestRate, 4); // Round to 4 decimal places
$vbLabelText   $csharpLabel

用户界面显示

在用户界面中显示数值时,为了提高可读性,通常会将数字四舍五入。 使用 Math.Round 进行四舍五入可以提高所呈现信息的清晰度。

double temperature = 23.678;
double roundedTemperature = Math.Round(temperature, 1); // Round to 1 decimal place
double temperature = 23.678;
double roundedTemperature = Math.Round(temperature, 1); // Round to 1 decimal place
$vbLabelText   $csharpLabel

统计分析

在统计分析中,精确的四舍五入对于避免引入偏差或误差至关重要。 Math.Round 方法可以帮助以所需的精确度呈现结果。

double meanValue = CalculateMean(data);
double roundedMean = Math.Round(meanValue, 2); // Round mean value to 2 decimal places
double meanValue = CalculateMean(data);
double roundedMean = Math.Round(meanValue, 2); // Round mean value to 2 decimal places
$vbLabelText   $csharpLabel

科学计算

在科学应用领域,准确性至关重要。 在处理实验数据或科学计算时,使用 Math.Round 进行四舍五入可确保以有意义且准确的方式呈现结果。

double experimentalResult = 9.87654321;
double roundedResult = Math.Round(experimentalResult, 5); // Round to 5 decimal places
double experimentalResult = 9.87654321;
double roundedResult = Math.Round(experimentalResult, 5); // Round to 5 decimal places
$vbLabelText   $csharpLabel

数学建模

在实施数学模型或模拟时,四舍五入可以简化复杂的计算。 在建模过程中,可以使用 Math.Round 方法来控制中间结果的精度。

double modelResult = SimulatePhysicalSystem(parameters);
double roundedModelResult = Math.Round(modelResult, 3); // Round to 3 decimal places
double modelResult = SimulatePhysicalSystem(parameters);
double roundedModelResult = Math.Round(modelResult, 3); // Round to 3 decimal places
$vbLabelText   $csharpLabel

游戏开发

在游戏开发中,数字精度对于物理计算、定位和其他数学运算至关重要。 Math.Round 方法可确保与游戏相关的数值四舍五入到适当的精度水平。

double playerPosition = CalculatePlayerPosition();
double roundedPosition = Math.Round(playerPosition, 2); // Round to 2 decimal places
double playerPosition = CalculatePlayerPosition();
double roundedPosition = Math.Round(playerPosition, 2); // Round to 2 decimal places
$vbLabelText   $csharpLabel

在上述每个场景中,Math.Round 方法都允许开发人员控制数值的精度,从而提高应用程序的准确性和可读性。

IronPDF 简介

IronPdf 的核心功能是其HTML 转 PDF 功能,可保持布局和样式。 它可以将网页内容转换成 PDF,非常适合报告、发票和文档。 您可以轻松将 HTML 文件、URL 和 HTML 字符串转换为 PDF。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
$vbLabelText   $csharpLabel

现在,让我们看看如何使用 IronPDF 的 Iron Software C# PDF 库生成 PDF 文档。

安装

您可以选择通过 NuGet 包管理器控制台或 Visual Studio 包管理器安装 IronPDF。

Install-Package IronPdf

在搜索栏中搜索 "ironpdf",使用 NuGet 包管理器安装 IronPdf。

使用IronPDF生成PDF

using IronPdf;

List<string> cart = new List<string>();

void AddItems(params string[] items)
{
    for (int i = 0; i < items.Length; i++)
    {
        cart.Add(items[i]);
    }
}

Console.WriteLine("Enter the cart items as comma-separated values:");
var itemsString = Console.ReadLine();
if (itemsString != null)
{
    var items = itemsString.Split(",").ToArray();
    AddItems(items);
}

AddItems("Sample1", "Sample2");

Console.WriteLine("-------------------------------------------------------");
Console.WriteLine("Display Cart");

string name = "Sam";
var count = cart.Count;
string content = $@"
<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} items in the cart.</p>
" + string.Join("\n", cart.Select(x => $"<p>{x}</p>"))
+ @"
</body>
</html>";

var pdfRenderer = new ChromePdfRenderer();
pdfRenderer.RenderHtmlAsPdf(content).SaveAs("cart.pdf");
using IronPdf;

List<string> cart = new List<string>();

void AddItems(params string[] items)
{
    for (int i = 0; i < items.Length; i++)
    {
        cart.Add(items[i]);
    }
}

Console.WriteLine("Enter the cart items as comma-separated values:");
var itemsString = Console.ReadLine();
if (itemsString != null)
{
    var items = itemsString.Split(",").ToArray();
    AddItems(items);
}

AddItems("Sample1", "Sample2");

Console.WriteLine("-------------------------------------------------------");
Console.WriteLine("Display Cart");

string name = "Sam";
var count = cart.Count;
string content = $@"
<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} items in the cart.</p>
" + string.Join("\n", cart.Select(x => $"<p>{x}</p>"))
+ @"
</body>
</html>";

var pdfRenderer = new ChromePdfRenderer();
pdfRenderer.RenderHtmlAsPdf(content).SaveAs("cart.pdf");
$vbLabelText   $csharpLabel

在上述代码中,我们正在为购物车项目生成 HTML 文档,然后使用 IronPDF 将其保存为 PDF 文档。

输出

!a href="/static-assets/pdf/blog/math-round-csharp/math-round-csharp-3.webp">Math.Round C#(如何为开发人员工作):图 3 - 上述代码的输出。

许可(提供免费试用)

要启用所提供代码的功能,必须获得许可证密钥。 您可以从此处获取试用密钥,必须将其插入到 appsettings.json 文件中。

"IronPdf.LicenseKey": "your license key"

提供您的电子邮件 ID 以获取试用许可证。

结论

总之,C# 中的 Math.Round 方法是对双数值和小数值进行四舍五入的通用工具,它为开发人员提供了将数值四舍五入到最接近的整数或指定小数位数的灵活性。 了解 Math.Round 的复杂性,包括其对中点值的处理和 MidpointRounding 策略的使用,对于在 C# 编程中进行准确可靠的数学运算至关重要。 无论是处理财务计算、用户界面显示,还是其他需要精确数字表示的场景,Math.Round 方法都是程序员工具包中不可或缺的资产。 此外,我们还看到 IronPDF 是如何生成 PDF 文档的多功能库。

常见问题解答

如何在 C# 中的财务计算中使用 Math.Round?

Math.Round 常用于财务计算中,以确保精确性,特别是在利率计算、货币转换和税务计算等操作中。通过四舍五入到指定的小数位数,它有助于保持数值的完整性。

C# 中的 MidpointRounding 是什么,它如何影响四舍五入?

MidpointRounding 是 C# 中的一个枚举,当一个值正好位于两个数字之间时,它会影响四舍五入的执行。它提供了诸如 MidpointRounding.AwayFromZero(远离零四舍五入)和 MidpointRounding.ToEven(四舍五入到最近的偶数)等策略,以最小化累计舍入误差。

Math.Round 在用户界面设计中如何使用?

在用户界面设计中,Math.Round 用于通过将数值四舍五入到指定的小数位数来改善显示,确保为最终用户清晰准确地呈现信息。

Math.Round 方法如何处理 C# 中的 double 和 decimal 数据类型?

Math.Round 方法可以通过将 double 和 decimal 数据类型四舍五入到最近的整数值或指定的小数位数来处理。这种灵活性对于数学计算中的精确性至关重要。

Math.Round 可用于科学计算吗?

是的,Math.Round 使用于科学计算中,将数值结果四舍五入到所需的精确度,确保大量计算和数据分析的准确性。

在 C# 应用程序中使用 IronPDF 的好处是什么?

IronPDF 是一个 C# 库,可以让开发人员将 HTML 内容转换为 PDF。它在生成报告、发票和文档方面非常有利,是处理 C# 应用程序中 PDF 操作的必备工具。

MidpointRounding.ToEven 如何在 C# 中工作?

MidpointRounding.ToEven,也称为银行家的舍入,将中点值四舍五入到最近的偶数。此方法减少了累计舍入误差,尤其是在重复计算中,是金融和统计应用的有效工具。

Math.Round 适用于 C# 的游戏开发吗?

是的,Math.Round 适用于游戏开发,因为它有助于物理计算、定位以及其他重要的数学操作,以确保流畅的游戏体验。

Jacob Mellor,Team Iron 的首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技术官,是 C# PDF 技术的先锋工程师。作为 Iron Software 核心代码库的原始开发者,自公司成立以来,他就塑造了公司的产品架构,并与首席执行官 Cameron Rimington 一起将其转变成一家公司,拥有50多人,服务于 NASA、特斯拉和全球政府机构。

Jacob 拥有曼彻斯特大学 (1998-2001) 的一级荣誉土木工程学士学位。1999 年在伦敦创办了自己的第一家软件公司,并于 2005 年创建了他的第一个 .NET 组件后,他专注于解决微软生态系统中的复杂问题。

他的旗舰 IronPDF 和 Iron Suite .NET 库在全球已获得超过 3000 万次的 NuGet 安装,其基础代码继续为全球使用的开发者工具提供支持。拥有 25 年商业经验和 41 年编程经验的 Jacob 仍专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。