跳過到頁腳內容
.NET幫助

C# 四捨五入(開發者的工作原理)

四捨五入是一個基本的數學概念,經常應用在現實世界的情境中。 在 C# 中,Math.Round方法可讓您將數值四捨五入到最接近的整數值或特定的小數位數,為此提供便利。 本教程深入探討了 C# 中的四捨五入細微差別,並說明了如何利用這個強大的方法。

四捨五入簡介

四捨五入是指將數字調整到最接近的整數或小數值,使其更簡單或符合特定要求。 例如,當您有十進位數字 3.14159 時,四捨五入到小數點後兩位會產生 3.14

Why Round Numbers?

1.簡潔性:四捨五入的數字通常更容易閱讀和理解。 2.精確度:在某些情況下,對四捨五入的數值進行操作比精確的數值更有效率,尤其是在貨幣計算等情況下。

常見的捨入情況

1.最近整數:將小數值四捨五入為最接近的整數。 2.指定的小數點數目:將一個數字四捨五入到指定的小數位數,例如將 15.678 四捨五入到小數點後兩位就是 15.68

C# 中四捨五入的基本原理;

C# 透過 Math.Round 方法提供強大的四捨五入系統。 此方法可接受各種參數,以自訂四捨五入的操作。

求最近的整數值

Math.Round 方法的最簡單形式是將一個 double 值四捨五入為最接近的整數值。 如果給定的數字與兩個整數等距,則四捨五入到最接近的偶數,通常稱為 "銀行家的四捨五入"。

double originalValue = 4.5;
double roundedValue = Math.Round(originalValue);
Console.WriteLine($"Original: {originalValue}, Rounded: {roundedValue}");
double originalValue = 4.5;
double roundedValue = Math.Round(originalValue);
Console.WriteLine($"Original: {originalValue}, Rounded: {roundedValue}");
Dim originalValue As Double = 4.5
Dim roundedValue As Double = Math.Round(originalValue)
Console.WriteLine($"Original: {originalValue}, Rounded: {roundedValue}")
$vbLabelText   $csharpLabel

在上面的例子中,4.545 相等。 由於 4 是最接近的偶數,因此該方法會返回 4

重整為特定的小數位數

您也可以使用額外的參數,將雙精度浮點數四捨五入到指定的小數位數:

double value = 7.34567;
double rounded = Math.Round(value, 2); // Rounds to two decimal places
Console.WriteLine($"Original: {value}, Rounded: {rounded}");
double value = 7.34567;
double rounded = Math.Round(value, 2); // Rounds to two decimal places
Console.WriteLine($"Original: {value}, Rounded: {rounded}");
Dim value As Double = 7.34567
Dim rounded As Double = Math.Round(value, 2) ' Rounds to two decimal places
Console.WriteLine($"Original: {value}, Rounded: {rounded}")
$vbLabelText   $csharpLabel

該方法將原始值 7.34567 四捨五入到 7.35 中,因為我們指定它要四捨五入到小數點後兩位。

中點捨入模式

當處理中點值(與兩個可能捨入的值等距的值)時,C# 提供 MidpointRounding 模式來決定這些值的捨入方式。

預設捨入

預設情況下,Math.Round 會將中點值四捨五入為最接近的偶數。

double valueOne = Math.Round(4.5);  // Rounded to 4
double valueTwo = Math.Round(5.5);  // Rounded to 6
double valueOne = Math.Round(4.5);  // Rounded to 4
double valueTwo = Math.Round(5.5);  // Rounded to 6
Dim valueOne As Double = Math.Round(4.5) ' Rounded to 4
Dim valueTwo As Double = Math.Round(5.5) ' Rounded to 6
$vbLabelText   $csharpLabel

指定 MidpointRounding 模式。

為了對中點值的四捨五入操作提供更多控制,您可以傳入特定的 MidpointRounding 模式作為參數:

double value = 5.5;
double rounded = Math.Round(value, 0, MidpointRounding.AwayFromZero);
Console.WriteLine($"Original: {value}, Rounded: {rounded}");
double value = 5.5;
double rounded = Math.Round(value, 0, MidpointRounding.AwayFromZero);
Console.WriteLine($"Original: {value}, Rounded: {rounded}");
Dim value As Double = 5.5
Dim rounded As Double = Math.Round(value, 0, MidpointRounding.AwayFromZero)
Console.WriteLine($"Original: {value}, Rounded: {rounded}")
$vbLabelText   $csharpLabel

在這個範例中,MidpointRounding.AwayFromZero 模式會確保數字四捨五入至 6

以小數值使用 Math.Round

雖然我們已討論過雙倍值的四捨五入,但 C# 也支援小數值的四捨五入。 方法類似,但它們使用十進制的資料類型。 以下是一個範例:

decimal decimalValue = 5.678m;
decimal roundedDecimal = Math.Round(decimalValue, 1); // Rounds to one decimal place
Console.WriteLine($"Original: {decimalValue}, Rounded: {roundedDecimal}");
decimal decimalValue = 5.678m;
decimal roundedDecimal = Math.Round(decimalValue, 1); // Rounds to one decimal place
Console.WriteLine($"Original: {decimalValue}, Rounded: {roundedDecimal}");
Dim decimalValue As Decimal = 5.678D
Dim roundedDecimal As Decimal = Math.Round(decimalValue, 1) ' Rounds to one decimal place
Console.WriteLine($"Original: {decimalValue}, Rounded: {roundedDecimal}")
$vbLabelText   $csharpLabel

小數位數字 5.678 四捨五入到小數點後一位數為 5.7

自訂捨入函數

有時候,您可能需要執行標準 Math.Round 方法未涵蓋的特定四捨五入操作。 撰寫自訂捨入函數可讓您完全控制過程。

重整。

若要始終四捨五入到最接近的整數,您可以使用 Math.Ceiling 方法:

double value = 4.3;
double roundedUp = Math.Ceiling(value);
Console.WriteLine($"Original: {value}, Rounded Up: {roundedUp}");
double value = 4.3;
double roundedUp = Math.Ceiling(value);
Console.WriteLine($"Original: {value}, Rounded Up: {roundedUp}");
Dim value As Double = 4.3
Dim roundedUp As Double = Math.Ceiling(value)
Console.WriteLine($"Original: {value}, Rounded Up: {roundedUp}")
$vbLabelText   $csharpLabel

小數位 4.3 四捨五入為 5

向下滾動

相反地,向下捨入到最接近的整數值是使用 Math.Floor 方法來完成的:

double value = 4.7;
double roundedDown = Math.Floor(value);
Console.WriteLine($"Original: {value}, Rounded Down: {roundedDown}");
double value = 4.7;
double roundedDown = Math.Floor(value);
Console.WriteLine($"Original: {value}, Rounded Down: {roundedDown}");
Dim value As Double = 4.7
Dim roundedDown As Double = Math.Floor(value)
Console.WriteLine($"Original: {value}, Rounded Down: {roundedDown}")
$vbLabelText   $csharpLabel

小數位 4.7 向下捨入為 4

使用字串輸入工作

在許多應用程式中,您可能會以字串的形式處理數值。 將字串解析成雙數或十進制、四捨五入,然後再轉換回來,可以使用 C# 來完成。

解析與捨入

以下是如何將包含小數的字串四捨五入的範例:

string originalString = "4.5678";
double parsedValue = double.Parse(originalString);
double rounded = Math.Round(parsedValue, 2); // Rounds to two decimal places
string roundedString = rounded.ToString();
Console.WriteLine($"Original: {originalString}, Rounded: {roundedString}");
string originalString = "4.5678";
double parsedValue = double.Parse(originalString);
double rounded = Math.Round(parsedValue, 2); // Rounds to two decimal places
string roundedString = rounded.ToString();
Console.WriteLine($"Original: {originalString}, Rounded: {roundedString}");
Dim originalString As String = "4.5678"
Dim parsedValue As Double = Double.Parse(originalString)
Dim rounded As Double = Math.Round(parsedValue, 2) ' Rounds to two decimal places
Dim roundedString As String = rounded.ToString()
Console.WriteLine($"Original: {originalString}, Rounded: {roundedString}")
$vbLabelText   $csharpLabel

原文: 4.5678, 四捨五入: 4.57

金融應用程式中的鑲邊

在處理金融應用程式時,精確度是至關重要的。 捨入錯誤可能會導致重大問題。 在這種情況下,由於十進制的精確度比 double 高,因此十進制是首選。

貨幣四捨五入範例

以下範例展示了代表貨幣的小數值的四捨五入:

decimal originalValue = 1234.5678m;
decimal roundedValue = Math.Round(originalValue, 2, MidpointRounding.AwayFromZero);
Console.WriteLine($"Original: {originalValue:C}, Rounded: {roundedValue:C}");
decimal originalValue = 1234.5678m;
decimal roundedValue = Math.Round(originalValue, 2, MidpointRounding.AwayFromZero);
Console.WriteLine($"Original: {originalValue:C}, Rounded: {roundedValue:C}");
Dim originalValue As Decimal = 1234.5678D
Dim roundedValue As Decimal = Math.Round(originalValue, 2, MidpointRounding.AwayFromZero)
Console.WriteLine($"Original: {originalValue:C}, Rounded: {roundedValue:C}")
$vbLabelText   $csharpLabel

上述程式碼將數值四捨五入至小數點後兩位,符合大多數貨幣標準。

偵錯與疑難排解捨入錯誤

偶爾,四捨五入的運算可能無法得到預期的結果。 這些差異可能是由於浮點精確度與雙重值等問題造成的。

常見陷阱

  • Double Precision:double 類型可能無法總是精確地表示十進位數字,導致意外的四捨五入結果。 使用十進制可以減輕這種情況。
  • 不正確的 MidpointRounding 模式:確保您使用正確的 MidpointRounding 模式來滿足您的特定需求。 誤用這些模式會導致四捨五入的錯誤。

如何調試

利用日誌和斷點等工具追蹤捨入前後的值。 檢查原始值和傳給四捨五入方法的參數通常可以發現不一致的地方。

Iron Suite

在掌握 C# 中四捨五入的基礎知識後,您可能會想知道如何讓您的應用程式更上一層樓,尤其是在處理複雜的資料格式時。 Iron Suite 在此可成為您的救星。 此套件包括 IronPDF、IronXL、IronOCR 和 IronBarcode 等功能強大的工具。 讓我們深入探討這些工具如何與您的捨入作業整合,並進一步豐富您的應用程式。

IronPDF。

C# Round (How It Works For Developers) Figure 1

IronPDF是一個強大的 C# 函式庫,專為從 HTML 產生 PDF、編輯和管理而設計。 試想一下,您需要在執行四捨五入運算後產生 PDF 格式的報告。 IronPDF 可以毫不費力地將您的 C# 程式碼轉換成高品質的 PDF。

using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Sample data for invoice
        decimal itemPrice = 49.995m; // Item price before rounding
        decimal taxRate = 0.18m;     // 18% tax rate

        // Round price to 2 decimal places
        decimal roundedPrice = Math.Round(itemPrice, 2);

        // Calculate and round the tax amount
        decimal taxAmount = Math.Round(roundedPrice * taxRate, 2);

        // Calculate the total amount
        decimal totalAmount = Math.Round(roundedPrice + taxAmount, 2);

        // Create simple HTML content for the PDF
        string htmlContent = $@"
            <h1>Invoice</h1>
            <p>Item Price: ${roundedPrice}</p>
            <p>Tax (18%): ${taxAmount}</p>
            <hr>
            <h2>Total Amount: ${totalAmount}</h2>
        ";

        // Generate PDF using IronPDF
        var renderer = new ChromePdfRenderer();
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF file
        pdfDocument.SaveAs("Invoice.pdf");

        Console.WriteLine("PDF invoice generated successfully with rounded values.");
    }
}
using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Sample data for invoice
        decimal itemPrice = 49.995m; // Item price before rounding
        decimal taxRate = 0.18m;     // 18% tax rate

        // Round price to 2 decimal places
        decimal roundedPrice = Math.Round(itemPrice, 2);

        // Calculate and round the tax amount
        decimal taxAmount = Math.Round(roundedPrice * taxRate, 2);

        // Calculate the total amount
        decimal totalAmount = Math.Round(roundedPrice + taxAmount, 2);

        // Create simple HTML content for the PDF
        string htmlContent = $@"
            <h1>Invoice</h1>
            <p>Item Price: ${roundedPrice}</p>
            <p>Tax (18%): ${taxAmount}</p>
            <hr>
            <h2>Total Amount: ${totalAmount}</h2>
        ";

        // Generate PDF using IronPDF
        var renderer = new ChromePdfRenderer();
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF file
        pdfDocument.SaveAs("Invoice.pdf");

        Console.WriteLine("PDF invoice generated successfully with rounded values.");
    }
}
Imports IronPdf
Imports System

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Sample data for invoice
		Dim itemPrice As Decimal = 49.995D ' Item price before rounding
		Dim taxRate As Decimal = 0.18D ' 18% tax rate

		' Round price to 2 decimal places
		Dim roundedPrice As Decimal = Math.Round(itemPrice, 2)

		' Calculate and round the tax amount
		Dim taxAmount As Decimal = Math.Round(roundedPrice * taxRate, 2)

		' Calculate the total amount
		Dim totalAmount As Decimal = Math.Round(roundedPrice + taxAmount, 2)

		' Create simple HTML content for the PDF
		Dim htmlContent As String = $"
            <h1>Invoice</h1>
            <p>Item Price: ${roundedPrice}</p>
            <p>Tax (18%): ${taxAmount}</p>
            <hr>
            <h2>Total Amount: ${totalAmount}</h2>
        "

		' Generate PDF using IronPDF
		Dim renderer = New ChromePdfRenderer()
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

		' Save the PDF file
		pdfDocument.SaveAs("Invoice.pdf")

		Console.WriteLine("PDF invoice generated successfully with rounded values.")
	End Sub
End Class
$vbLabelText   $csharpLabel

IronXL。

C# Round (How It Works For Developers) 圖 2

IronXL 提供處理 Excel 檔案的功能,讓 C# 開發人員能夠無縫讀取、寫入和處理 Excel 試算表。 使用 IronXL,您可以從 Excel 表單中擷取十位數或雙倍數的資料,在 C# 中執行四捨五入的操作。

IronOCR。

C# Round (How It Works For Developers) 圖 3

IronOCR是用於 C# 的高級光學字元識別 (OCR) 函式庫,可以從影像和 PDF 識別並擷取文字。 假設您有包含數值資料的掃描文件或影像。 使用 IronOCR,您可以在 C# 中提取這些資料、進行處理或捨棄。

IronBarcode。

C# Round (How It Works For Developers) 圖 4

IronBarcode是一款功能強大的工具,用於在 .NET 中生成、讀取和分類條碼和 QR 代碼。 在圓形資料需要編碼成 BarCode 的情況下(例如,零售應用程式中的產品價格),IronBarcode 可以發揮無價之寶。

結論

C# 中的捨入是一個多層面的主題,在各個領域中都有應用。 瞭解內建的方法,如 Math.Round, Math.Floor, 和 Math.Ceiling, 並知道何時使用適當的資料類型 (double 或 decimal) 將使您有能力有效率地處理數值資料。

在 C# 中使用四捨五入有助於使數字更容易處理。 但如果您想利用這些數字做更多的事情呢? 這就是 Iron Suite 的用武之地。 這是一套可以幫助您處理 PDF、Excel 檔案、影像中的文字以及 BarCode 的工具。

最令人興奮的部分來了:您可以使用 試用授權免費試用這些工具,看看您是否喜歡。 如果您決定購買,每一個都需要 liteLicense 的費用。 但如果您想全部購買,只需購買兩種工具即可獲得全套。 這就像得到四個工具,但只付兩個工具的費用! 請參閱 Iron Suite 的 授權頁面,以瞭解更多資訊。

常見問題解答

如何在 C# 中對金融應用程式中的數字進行四捨五入?

在 C# 中,您可以使用 `Math.Round` 方法與 `decimal` 資料類型,以在金融應用程式中達到更高的精確度。建議使用 `MidpointRounding.AwayFromZero`,以確保金融交易的準確四捨五入。

C# 的預設四捨五入模式是什麼?

C# 的預設四捨五入模式是「銀行家四捨五入」,使用「MidpointRounding.ToEven」選項將中點值四捨五入到最接近的偶數。

在 C# 中將 HTML 轉換為 PDF 時,四捨五入如何運作?

使用 IronPDF 將 HTML 轉換為 PDF 時,您可以在將數字資料渲染到 PDF 文件之前,先用 C# 處理這些資料,以加入數值資料的四捨五入運算。

我可以對 Excel 檔案中的資料使用 C# 捨入方法嗎?

是的,您可以使用 IronXL 在 C# 中處理 Excel 檔案,使用 `Math.Round` 對儲存格內的數值資料套用捨入方法,以達到精確的資料呈現。

C# 中 MidpointRounding 枚举的意义是什么?

C# 中的「MidpointRounding」枚舉提供了中點值四捨五入的選項,例如「AwayFromZero」和「ToEven」,讓開發人員可以控制如何將四捨五入套用到正好介於兩個整數之間的數字。

如何在 C# 中應用自訂捨入函數?

您可以透過編寫自己的邏輯,在 C# 中建立自訂的四捨五入函數,以處理標準 `Math.Round` 方法以外的特定四捨五入規則,這些函數可與 Iron Software 工具整合,以增強資料處理能力。

在 C# 中,字串輸入值可以四捨五入嗎?

是的,字串輸入可以在 C# 中解析成數字類型,例如 `double` 或 `decimal`,讓您可以套用四捨五入的方法,然後再轉換回字串以供進一步使用。

IronOCR 和 IronBarcode 等工具如何從四捨五入運算中獲益?

IronOCR 可以使用四捨五入來處理從文字辨識中擷取的數值資料,而 IronBarcode 則可以將四捨五入的數值整合到條碼資料中,以精確地編碼數值資訊。

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

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。