.NET 幫助

Math.Round C#(對開發人員的運作方式)

Chipego
奇佩戈·卡林达
2024年3月6日
分享:

在 C# 程式設計領域,Math.Round 值方法在四捨五入數值時扮演著關鍵角色,特別是處理 double 值和 decimal 值數據類型時。此方法允許開發者將給定的數值四捨五入到最近的整數值或指定數的更少小數位,從而在數學運算中提供靈活性和精確性。 有多種四捨五入類型可供選擇,例如 Midpoint Rounding。 在本文中,我們將深入探討 C# 中的 Math.Round 的複雜性,探索其各個方面及使用場景。 在本文的後續部分中,我們將探討使用IronPDF程式庫由Iron Software處理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 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

在此範例中,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

在這裡,使用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

在此範例中,當將值四捨五入到 5.5 時,MidpointRounding.ToEven 會朝向最接近的偶數進行四捨五入。(導致6),則 MidpointRounding.AwayFromZero 則是向零遠處取整,得到 5。

四捨五入到指定的小數位數

若要將數字四捨五入到指定的小數位數,Math.Round 方法允許包括一個表示整數位數的額外參數:

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

這裡,小數 9.123456 被四捨五入到小數點后三位,結果是 9.123。

C#中的中點值和四捨五入慣例

當結果的最低有效位數之後的值正好介於兩個數字之間的中點時,會產生一個中點值。 例如,2.56500 四捨五入到小數點後兩位是 2.57,而 3.500 四捨五入到整數是 4。在沒有明確的四捨五入慣例情況下,挑戰在於在四捨五入策略中識別最接近的中點值。

在C#中的Round方法支持兩種處理中點值的四捨五入約定:

遠離零的四捨五入:中間值進行四捨五入到遠離零的下一個數字。 例如,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);

輸出

Math.Round C#(對開發人員的運作方式):圖1 - 雙精度浮點輸出

中點取整模式

Math.Round C#(開發人員如何使用):圖 2 - 中點四捨五入

AwayFromZero:1

AwayFromZero 捨入策略是在一個數值位於兩個數之間的中間點時,將其捨入到最接近的數字。

ToZero: 2

此策略的特點是向零趨近的截尾取整。 結果是最接近且不大於無限精確結果的數值。

到偶數: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

在這個例子中,將 double 值 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

在這裡,值 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

用戶界面顯示

在使用者介面中呈現數值時,通常會將數字進行四捨五入以提高可讀性。 例如,在顯示溫度讀數或財務數據的儀表板中,使用 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

統計分析

在統計分析中,精確的四捨五入對於避免引入偏差或不準確性至關重要。 無論是計算平均值、中位數,還是其他統計指標,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

科學計算

在科學應用中,精確性至關重要。 在處理實驗數據或科學計算時,使用 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

數學建模

在實施數學模型或模擬時,四捨五入可能是簡化複雜計算所必需的。 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

遊戲開發

在遊戲開發中,數值精確性對於物理計算、定位和其他數學運算至關重要。 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

在每個這些情景中,Math.Round 方法使開發人員能夠控制數值的精確度,提升應用程式的準確性和可讀性。

介紹 IronPDF

IronPDF 的核心功能是其HTML轉PDF函數,保持佈局和樣式。 它將網頁內容轉換為 PDF,非常適合報告、發票和文件。 您可以輕鬆地將 HTML 文件、網址和 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");
    }
}

現在讓我們看看如何使用 IronPDF 生成 PDF 文件IronPDFC# PDF 庫 來自Iron Software.

安裝

您可以選擇透過NuGet套件管理器控制台或Visual Studio套件管理器安裝IronPDF。

dotnet add package IronPdf
dotnet add package IronPdf

使用 NuGet 套件管理員安裝 IronPDF,請在搜尋欄中搜尋 "ironpdf"。

使用 IronPDF 生成 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");
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");

在上面的程式碼中,我們正在生成購物車項目的HTML文件,然後使用IronPDF將其保存為PDF文件。

輸出

Math.Round C#(開發者使用方式):圖3 - 上述程式碼的輸出

授權(免費試用可用)

要啟用所提供程式碼的功能,必須取得授權金鑰。 您可以從此位置獲取試用金鑰這裡,必須插入到 appsettings.json 文件中。

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"

請提供您的電子郵件地址以獲取試用許可証。

結論

總結來說,在 C# 中的 Math.Round 方法是一個多功能的工具,用於對 double 和 decimal 值進行四捨五入,為開發人員提供了將值四捨五入到最接近的整數或指定的小數位數的靈活性。 了解 Math.Round 的精細之處,包括其對中點值的處理以及 MidpointRounding 策略的使用,對於 C# 程式設計中的準確和可靠的數學運算至關重要。 無論是處理財務計算、用戶界面顯示,還是其他需要精確數字表示的情況,Math.Round 方法在程式設計師的工具箱中都是不可或缺的資產。 此外,我們看到了IronPDF是個多功能的函式庫,可以用來生成PDF文件。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# 計時器(開發人員如何使用)
下一個 >
C# ArrayList(開發人員如何使用)