跳至頁尾內容
開發者更新

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

舍入數字是一個基本的數學概念,經常在現實世界中應用。 在C#中,Math.Round 方法透過允許您將值舍入到最接近的整數或特定的小數位數來促進這一點。 本教程深入探討C#中的舍入細節,並說明如何利用這個強大的方法。

舍入介紹

舍入一個數字意味著將其調整到最接近的整數或小數,以使其更簡單或符合特定要求。 例如,當您有小數3.14

為什麼要舍入數字?

  1. 簡單性:舍入的數字通常更易於閱讀和理解。
  2. 精度:在某些情況下,操作舍入的值而不是精確值更有效,尤其是在貨幣計算等情境中。

常見舍入場景

  1. 最接近的整數:將小數值舍入到其最接近的整數。
  2. 指定的小數位數:將一個數字舍入到特定的小數位數,例如將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

在上述範例中,5等距。 因為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.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

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

小數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

處理字串輸入

在許多應用程式中,您可能需要處理作為字串的數值。 可以使用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

在金融應用中的舍入

在處理金融應用時,精確度至關重要。 舍入錯誤可能會導致重大問題。 在此類情況下,由於其相比雙精度更高的精度,優先使用小數型別。

貨幣舍入範例

以下範例展示了舍入表示貨幣的小數值:

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

上述程式碼將值舍入到兩個小數位,以符合大多數貨幣標準。

除錯和排除舍入錯誤

有時,舍入操作可能無法產生預期的結果。 這些差異可能是由於雙精度值的浮點精度問題。

常見陷阱

  • 雙精度精度:雙精度型別可能無法總是準確表示小數,導致意外的舍入結果。 使用小數型別可以減輕這一問題。
  • 中點舍入模式錯誤:確保為您的特定需求使用正確的MidpointRounding模式。 誤用這些模式可能會導致舍入錯誤。

如何除錯

利用日誌和斷點等工具,去追踪舍入前後的值。 檢查原始值和傳遞給舍入方法的參數通常可以揭示不一致之處。

Iron Suite

在掌握C#中舍入的基礎知識後,您可能想知道如何將您的應用程式提升到更高水平,尤其是在處理複雜資料格式時。 Iron Suite可以在此處助您一臂之力。 這個套件包含諸如IronPDF、IronXL、IronOCR和IronBarcode等強大工具。 讓我們深入探討這些工具如何與您的舍入操作整合並進一步豐富您的應用程式。

IronPDF

C# Round(如何為開發人員運作)圖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(如何為開發人員運作)圖2

IronXL提供了處理Excel文件的功能,使C#開發者可以無縫地讀取、寫入和操作Excel電子表格。 使用IronXL,您可以從Excel表中獲取小數或雙精度資料,在C#中進行舍入操作。

IronOCR

C# Round(如何為開發人員運作)圖3

IronOCR是一個用於C#的先進光學字元識別(OCR)程式庫,可以從圖像和PDF中識別並提取文字。 假如您有包含數值資料的掃描文件或圖片。 使用IronOCR,您可以提取這些資料,並在C#中進行處理或舍入。

IronBarcode

C# Round(如何為開發人員運作)圖4

IronBarcode是一個用於在.NET中生成、讀取和分類條碼和QR碼的強大工具。 在需要將舍入資料編碼到條碼中的情境下(例如,在零售應用中進行產品定價),IronBarcode是無價之寶。

結論

在C#中進行舍入是一個具有多重面的主題,應用於各種領域。 了解內建的方法例如Math.Ceiling,並知道何時使用合適的資料型別(雙精度或小數),將使您能夠有效地處理數字資料。

在C#中舍入可以使數字變得更易於操作。 但如果您想對這些數字做更多事情呢? 這就是Iron Suite的用武之地。 這是一套可以幫助您處理PDF、Excel文件、圖像中文字與條碼的工具。

激動人心的部分來了:您可以用 試用授權 免費嘗試這些工具,看看您是否滿意。 如果您決定購買其中一個,每一個的價格是 liteLicense。 但是如果您想買下所有的,您可以只需兩款工具的價格得到整個套件。 這就像是獲得四個工具但只支付兩個的價錢! 查看Iron Suite的授權頁面以獲取更多資訊。

常見問題

如何在 C# 中將數字四捨五入以用於金融應用程式中?

在 C# 中,您可以使用 `Math.Round` 方法和 `decimal` 資料型別來實現更高精度的財務應用程式。建議使用 `MidpointRounding.AwayFromZero` 以確保金融交易的精確四捨五入。

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

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

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

using IronPDF 將 HTML 轉換為 PDF 時,可以通過在 C# 中處理資料來進行資料的四捨五入操作,然後將其渲染到 PDF 文件中。

我可以在 Excel 文件中的資料上使用 C# 的四捨五入方法嗎?

是的,您可以使用 IronXL 在 C# 中操作 Excel 文件,使用 `Math.Round` 對單元格中的資料進行四捨五入,以確保資料的準確展示。

C# 中的 MidpointRounding 列舉有什麼意義?

C# 中的 `MidpointRounding` 列舉提供了對中點值進行四捨五入的選項,例如 `AwayFromZero` 和 `ToEven`,使開發人員可以控制如何對恰好介於兩個整數之間的數字進行四捨五入。

如何在 C# 中應用自定義四捨五入函式?

您可以在 C# 中建立自定義四捨五入函式,通過編寫自己的邏輯來處理特定的四捨五入規則,超越標準的 `Math.Round` 方法,並可以與 Iron Software 工具整合以增強資料處理。

C# 能否對字串輸入值進行四捨五入?

可以,字串輸入能夠解析為 `double` 或 `decimal` 等數值型別,允許您使用四捨五入方法,然後將它們轉回字串以便進一步使用。

像 IronOCR 和 IronBarcode 這樣的工具如何受益於四捨五入操作?

IronOCR 可以利用四捨五入來處理從文字識別中提取的資料,而 IronBarcode 可以將四捨五入的值整合到條碼資料中,以準確編碼數字資訊。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

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