跳過到頁腳內容
.NET幫助

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

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

四捨五入簡介

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

Why Round Numbers?

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

常見的捨入情況

  1. 整:將小數四捨五入到最接近的整數。 2.指定小數位數:將數字四捨五入到指定的小數位數,例如將 15.678 四捨五入到兩位小數,則為 15.68

Basics of Rounding in C#

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

求最近的整數值

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

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 類型可能無法始終精確表示十進位數,從而導致意外的捨入結果。 使用 decimal 類型可以減輕這種情況。
  • 中點捨入模式不正確: 請確保根據特定要求使用正確的 MidpointRounding 模式。 誤用這些模式會導致捨入錯誤。

如何調試

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

Iron Suite

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

IronPDF

C# Round (How It Works For Developers) 圖 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 代碼。 在捨入資料需要編碼成條碼的情況下(例如,零售應用程式中的產品定價),IronBarcode 可以發揮極大的價值。

結論

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

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

最令人興奮的部分來了:您可以使用 試用授權免費試用這些工具,看看您是否喜歡。 如果您決定購買,每個工具的售價為 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# 中應用自定義四捨五入函數?

您可以通過編寫您自己的邏輯來創建自定義四捨五入函數,以處理超出標準 `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將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

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

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我