在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
在 C# 编程领域,Math.Round 值方法在数值四舍五入方面发挥着关键作用,尤其是在处理双数值和小数数值数据类型时。该方法允许开发人员将给定的数值舍入到最接近的整数值或指定的小数位数,为数学运算提供了灵活性和精确性。有多种四舍五入类型可供选择,如中点四舍五入。在本文中,我们将深入研究 C# 中 Math.Round 的复杂性,探索其各个方面和使用场景。在本文的后续章节中,我们将探索如何利用 IronPDF 图书馆 铁软件 用于处理 PDF 文件。
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 type of rounding method
Math.Round(Double, MidpointRounding) // MidpointRounding 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 type of rounding method
Math.Round(Double, MidpointRounding) // MidpointRounding 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 type of rounding method
'Math.Round(Double, MidpointRounding) // MidpointRounding 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)
'
在处理双数值时,Math.Round 通常用于将数字四舍五入为最接近的整数。例如
double originalValue = 3.75;
double roundedValue = Math.Round(originalValue);
// Output: 4
double originalValue = 3.75;
double roundedValue = Math.Round(originalValue);
// Output: 4
Dim originalValue As Double = 3.75
Dim roundedValue As Double = Math.Round(originalValue)
' Output: 4
在本例中,Math.Round 方法将原始的 double 值 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
Dim originalValue As Decimal = 8.625D
Dim roundedValue As Decimal = Math.Round(originalValue, 2)
' Output: 8.63
这里使用 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 = 5
double originalValue = 5.5;
double roundedValueEven = Math.Round(originalValue, MidpointRounding.ToEven);
double roundedValueOdd = Math.Round(originalValue, MidpointRounding.AwayFromZero);
// Output: roundedValueEven = 6, roundedValueOdd = 5
Dim originalValue As Double = 5.5
Dim roundedValueEven As Double = Math.Round(originalValue, MidpointRounding.ToEven)
Dim roundedValueOdd As Double = Math.Round(originalValue, MidpointRounding.AwayFromZero)
' Output: roundedValueEven = 6, roundedValueOdd = 5
在本例中,将数值舍入到 5.5 时,MidpointRounding.ToEven 向最接近的偶数舍入 (导致 6)而 MidpointRounding.AwayFromZero 则从 0 开始舍入,得到 5。
要将一个数字四舍五入到指定的小数位数,Math.Round 方法允许包含一个表示 int 位数的附加参数:
decimal originalValue = 9.123456m;
decimal roundedValue = Math.Round(originalValue, 3); // round values
// Output: 9.123
decimal originalValue = 9.123456m;
decimal roundedValue = Math.Round(originalValue, 3); // round values
// Output: 9.123
Dim originalValue As Decimal = 9.123456D
Dim roundedValue As Decimal = Math.Round(originalValue, 3) ' round values
' Output: 9.123
这里,十进制数 9.123456 四舍五入到小数点后三位,得出四舍五入后的数值 9.123。
当结果中最小有效数字后的数值正好位于两个数的中间时,就产生了中点值。例如,2.56500 四舍五入到小数点后两位 2.57 时是中点值,3.500 四舍五入到整数 4 时是中点值。在没有定义四舍五入惯例的情况下,如何在四舍五入策略中识别最接近中点值的值是一个难题。
C# 中的四舍五入方法支持两种处理中点值的四舍五入约定:
从零开始四舍五入:中点值四舍五入到从零开始的下一个数字。例如,3.75 向上舍入为 3.8,3.85 向上舍入为 3.9,-3.75 向下舍入为 -3.8,-3.85 向下舍入为 -3.9。该方法由 MidpointRounding.AwayFromZero 枚举成员表示。
四舍五入到最近的偶数 (银行家四舍五入):中点值四舍五入为最接近的偶数。实例包括将 3.75 和 3.85 四舍五入为 3.8,以及将 -3.75 和 -3.85 四舍五入为 -3.8。这种四舍五入方法由 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;
}
// print
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);
}
// print
Console.WriteLine("AwayFromZero: {0:N2}", sum / decimalSampleValues.Length);
// Calculate mean values with rounding to nearest.
sum = 0;
foreach (var value in decimalSampleValues)
{
sum += Math.Round(value, 1, MidpointRounding.ToEven);
}
// print
Console.WriteLine("ToEven: {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;
}
// print
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);
}
// print
Console.WriteLine("AwayFromZero: {0:N2}", sum / decimalSampleValues.Length);
// Calculate mean values with rounding to nearest.
sum = 0;
foreach (var value in decimalSampleValues)
{
sum += Math.Round(value, 1, MidpointRounding.ToEven);
}
// print
Console.WriteLine("ToEven: {0:N2}", sum / decimalSampleValues.Length);
Dim decimalSampleValues() As Decimal = { 1.15D, 1.25D, 1.35D, 1.45D, 1.55D, 1.65D }
Dim sum As Decimal = 0
' Calculate true mean values.
For Each value In decimalSampleValues
sum += value
Next value
' print
Console.WriteLine("True mean values: {0:N2}", sum / decimalSampleValues.Length)
' Calculate mean values with rounding away from zero.
sum = 0
For Each value In decimalSampleValues
sum += Math.Round(value, 1, MidpointRounding.AwayFromZero)
Next value
' print
Console.WriteLine("AwayFromZero: {0:N2}", sum / decimalSampleValues.Length)
' Calculate mean values with rounding to nearest.
sum = 0
For Each value In decimalSampleValues
sum += Math.Round(value, 1, MidpointRounding.ToEven)
Next value
' print
Console.WriteLine("ToEven: {0:N2}", sum / decimalSampleValues.Length)
AwayFromZero 四舍五入策略是在一个数字位于两个数字中间时,将其舍入到最接近的数字。
这种策略的特点是定向四舍五入归零。四舍五入的结果最接近无限精确的结果,但幅度不会大于无限精确的结果。
这种策略是四舍五入到最接近的数字,当一个数字位于两个数字的中间时,它就会被四舍五入到最接近的偶数。
这种策略要求向下舍入,结果最接近但不大于无限精确的结果。
这种策略是向上舍入,其结果最接近无限精确的结果,但也不小于无限精确的结果。
在处理双精度浮点数时,必须了解浮点表示法的性质可能导致的不精确问题。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
Dim originalValue As Double = 123.456789
Dim result As Double = Math.Round(originalValue, 4)
' Output: 123.4568, rounded value
在本例中,双数值 123.456789 四舍五入到小数点后四位,得到更精确的数值 123.4568。
当一个分数值正好位于两个整数的中间时,中点舍入策略就变得至关重要。Math.Round 方法采用指定的中点舍入策略来解决这种情况。
下面是一个使用中点四舍五入的例子:
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
Dim originalValue As Double = 7.5
Dim roundedValue As Double = Math.Round(originalValue, MidpointRounding.AwayFromZero)
' Output: 8
在这里,数值 7.5 从零四舍五入,得到四舍五入后的数值 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
Dim interestRate As Double = 0.04567
Dim roundedInterest As Double = Math.Round(interestRate, 4) ' Round to 4 decimal places
在用户界面中显示数值时,通常会对数字进行四舍五入以提高可读性。例如,在显示温度读数或财务数据的仪表板中,使用 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
Dim temperature As Double = 23.678
Dim roundedTemperature As Double = Math.Round(temperature, 1) ' Round to 1 decimal place
在统计分析中,精确的四舍五入对于避免引入偏差或误差至关重要。无论是计算平均值、中位数还是其他统计量,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
Dim meanValue As Double = CalculateMean(data)
Dim roundedMean As Double = Math.Round(meanValue, 2) ' Round mean value to 2 decimal places
在科学应用中,精度至关重要。在处理实验数据或科学计算时,使用 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
Dim experimentalResult As Double = 9.87654321
Dim roundedResult As Double = Math.Round(experimentalResult, 5) ' Round to 5 decimal places
在执行数学模型或模拟时,需要使用四舍五入来简化复杂的计算。在建模过程中,可以使用 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
Dim modelResult As Double = SimulatePhysicalSystem(parameters)
Dim roundedModelResult As Double = Math.Round(modelResult, 3) ' Round to 3 decimal places
在游戏开发中,数值精度对于物理计算、定位和其他数学运算至关重要。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
Dim playerPosition As Double = CalculatePlayerPosition()
Dim roundedPosition As Double = Math.Round(playerPosition, 2) ' Round to 2 decimal places
在上述每种情况下,Math.Round 方法都允许开发人员控制数值的精度,从而提高应用程序的准确性和可读性。
IronPDF 的核心功能是它的 HTML 转 PDF 功能,保持布局和样式。它能将网页内容转换为 PDF,非常适用于报告、发票和文档。你可以轻松地将 HTML 文件、URL 和 HTML 字符串转换为 PDF。
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. 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");
// 2. 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");
// 3. 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();
// 1. 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");
// 2. 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");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class
现在让我们看看如何使用以下工具生成 PDF 文档 IronPDF C# PDF 库来自 铁软件.
您可以选择通过 NuGet 包管理器控制台或 Visual Studio 包管理器安装 IronPDF。
dotnet add package IronPdf
dotnet add package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf
在搜索栏中搜索 "ironpdf",使用 NuGet 包管理器安装 IronPDF。
Console.WriteLine("Params Example");
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 ");
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>";
// Create a new PDF document
var pdfDocument = new ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(content).SaveAs("cart.pdf");
Console.WriteLine("Params Example");
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 ");
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>";
// Create a new PDF document
var pdfDocument = new ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(content).SaveAs("cart.pdf");
Imports Microsoft.VisualBasic
Console.WriteLine("Params Example")
Dim cart As New List(Of String)()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'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 ")
Dim itemsString = Console.ReadLine()
If itemsString IsNot Nothing Then
Dim items = itemsString.Split(",").ToArray()
AddItems(items)
End If
AddItems("Sample1", "Sample2")
Console.WriteLine("-------------------------------------------------------")
Console.WriteLine("Display Cart")
Dim name As String = "Sam"
Dim count = cart.Count
Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} items in the cart.</p>
" & String.Join(vbLf, cart.Select(Function(x) $"<p>{x}</p>")) & "
</body>
</html>"
' Create a new PDF document
Dim pdfDocument = New ChromePdfRenderer()
pdfDocument.RenderHtmlAsPdf(content).SaveAs("cart.pdf")
在上述代码中,我们为购物车项目生成 HTML 文档,然后使用 IronPDF 将其保存为 PDF 文档。
要启用所提供代码的功能,必须获取许可证密钥。您可以从以下位置获取试用密钥 *这里***必须插入到 appsettings.json 文件中。
"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
提供您的电子邮件 ID,即可获得试用版许可证。
总之,C# 中的 Math.Round 方法是对双数值和小数值进行四舍五入的通用工具,它为开发人员提供了将数值四舍五入到最接近整数或指定小数位数的灵活性。了解 Math.Round 的复杂性,包括它对中点值的处理和 MidpointRounding 策略的使用,对于在 C# 编程中进行准确可靠的数学运算至关重要。无论是处理财务计算、用户界面显示还是其他需要精确数字表示的情况,Math.Round 方法都是程序员工具包中不可或缺的资产。此外,我们还看到了 IronPDF 如何成为生成 PDF 文档的多功能库。