.NET 幫助

C# 四捨五入到小數點後第 2 位(開發人員如何操作)

發佈 2024年4月29日
分享:

四捨五入數字 在編程中,特別是當您處理金融數據或需要精確到一定小數位的測量時,四捨五入是一個常見的任務。在 C# 中,有多種方法可以將小數或雙精度數字四捨五入到小數點後兩位。本教程將清楚地解釋這些概念,並為您提供如何使用 C# 實現此精度的全面知識。我們會探討 IronPDF 以及由C#語言提供的各種方法和函數,使小數精確到指定的精度。

理解C#中的Decimal和Double數值類型

在深入探討數字的四捨五入技巧之前,了解我們將處理的數字類型是很重要的。在C#中,decimaldouble是用於數值的兩種類型。decimal變量通常用於需要最高精度的情況,例如財務計算。另一方面,double結果用於浮點計算足夠且性能比精確度更為重要的情況。這兩種類型都可以使用C#庫中的特定方法進行四捨五入。

使用 Math.Round 取到小數點後兩位

Math.Round 方法是將十進制值或雙精度值四捨五入到指定小數位數的最直接方法。您還可以使用此數學函數將雙精度值四捨五入到最接近的整數。這個 Math.Round 方法非常靈活,因為它允許您指定小數點後要保留的位數,而且在數字精確處於兩個區間之間時,也允許您選擇四捨五入的策略。

將小數值四捨五入到小數點位數

若要將小數四捨五入到小數點後兩位,可以使用 Math.Round 方法,此方法接受兩個參數:要四捨五入的數字和小數點位數。以下是一個簡單的範例:

decimal d = 3.14519M; // decimal number
decimal roundedValue = Math.Round(d, 2);
Console.WriteLine(roundedValue);  // Outputs: 3.15
decimal d = 3.14519M; // decimal number
decimal roundedValue = Math.Round(d, 2);
Console.WriteLine(roundedValue);  // Outputs: 3.15
Dim d As Decimal = 3.14519D ' decimal number
Dim roundedValue As Decimal = Math.Round(d, 2)
Console.WriteLine(roundedValue) ' Outputs: 3.15
VB   C#

在此範例中,十進位數值 3.14519 被四捨五入為 3.15。方法 Math.Round 會將十進位數 d 四捨五入到小數點後兩位。

C# 四捨五入到小數點後二位數(開發人員如何操作):圖 1 - 四捨五入到小數點後二位數示例輸出

四捨五入雙精度值

四捨五入雙精度值與四捨五入小數值類似。以下是如何使用數學函數將雙精度數字四捨五入到小數點後兩位的程式碼:

double num = 3.14519;
double result = Math.Round(num, 2); // round to 2 digits
Console.WriteLine(result);  // Output: 3.15
double num = 3.14519;
double result = Math.Round(num, 2); // round to 2 digits
Console.WriteLine(result);  // Output: 3.15
Dim num As Double = 3.14519
Dim result As Double = Math.Round(num, 2) ' round to 2 digits
Console.WriteLine(result) ' Output: 3.15
VB   C#

這段程式碼片段有效地將 double 數字 3.14519 四捨五入到最接近的整數 3.15,使用了 math.round 值。Math.Round 的第二個參數指定了四捨五入應該精確到小數點後兩位。

處理中點四捨五入

其中一個重要的四捨五入方面,是如何處理數字正好在兩個可能的四捨五入值之間的情況。C# 提供了一個選項,可以透過 MidpointRounding 列舉來指定四捨五入行為。這允許在這些情況下控制四捨五入的方向。

double midpointNumber = 2.345; // double value format
double midpointResult = Math.Round(midpointNumber, 2, MidpointRounding.AwayFromZero);
Console.WriteLine(midpointResult);  // Outputs answer: 2.35
double midpointNumber = 2.345; // double value format
double midpointResult = Math.Round(midpointNumber, 2, MidpointRounding.AwayFromZero);
Console.WriteLine(midpointResult);  // Outputs answer: 2.35
Dim midpointNumber As Double = 2.345 ' double value format
Dim midpointResult As Double = Math.Round(midpointNumber, 2, MidpointRounding.AwayFromZero)
Console.WriteLine(midpointResult) ' Outputs answer: 2.35
VB   C#

C# 四捨五入到小數點後兩位(對開發者的運作方式):圖2 - 中點四捨五入到小數點後兩位輸出

在上述範例中,MidpointRounding.AwayFromZero告知方法將中點數字 2.345 向遠離零的最近數字進行四捨五入,結果為 2.35。這在金融計算中特別有用,因為通常會使用向上取整。

使用 C# 和 IronPDF 進行數字取整及生成 PDF

C# 四捨五入至小數點後兩位(開發人員如何運作):圖3 - IronPDF

IronPDF 是一個專為 .NET 平台設計並使用 C# 編寫的綜合性 PDF 生成庫。它以其創建能力而廣受好評 通過渲染HTML生成高品質PDFCSS、JavaScript 和圖像。這一功能確保開發人員可以利用他們已有的網頁開發技能來生成 PDF。IronPDF 使用 Chrome 渲染引擎來生成像素完美的 PDF 文檔,鏡像顯示在網頁瀏覽器中看到的佈局。

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");
    }
}
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
VB   C#

IronPDF 可以無縫整合 C# 來處理精確的任務,例如在將小數嵌入 PDF 之前將其四捨五入到小數點後兩位。這在數字精確度很重要的財務報告或發票中尤其有用。

範例: 生成帶有四捨五入小數值的 PDF

在這個範例中,我們將創建一個簡單的 C# 應用程式,使用 IronPDF 來生成包含四捨五入到兩位小數的數字列表的 PDF 文件。這展示了如何在實際情境中將數值計算與 PDF 生成相結合。

首先,你需要安裝 IronPDF。你可以通過 NuGet 來完成這個操作:

Install-Package IronPdf

安裝 IronPDF 後,您可以這樣從 HTML 內容中生成 PDF,包括已四捨五入到小數點後兩位的數字:

using IronPdf;
using System;
class Program
{
    static void Main()
    {
        License.LicenseKey = "License-Key";
        // Create a PDF document
        var Renderer = new ChromePdfRenderer();
        // Sample data that might come from a database or computation
        double initialValue = 2.345678;
        double roundedValue = Math.Round(initialValue, 2);
        // HTML content including the rounded value
        var htmlContent = $@"
            <html>
            <head>
                <title>PDF Report</title>
            </head>
            <body>
                <h1>Financial Report</h1>
                <p>Value after rounding: {roundedValue}</p>
            </body>
            </html>";
        // Convert HTML to PDF
        var pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent);
        pdfDocument.SaveAs("Report.pdf");
        Console.WriteLine("PDF generated successfully.");
    }
}
using IronPdf;
using System;
class Program
{
    static void Main()
    {
        License.LicenseKey = "License-Key";
        // Create a PDF document
        var Renderer = new ChromePdfRenderer();
        // Sample data that might come from a database or computation
        double initialValue = 2.345678;
        double roundedValue = Math.Round(initialValue, 2);
        // HTML content including the rounded value
        var htmlContent = $@"
            <html>
            <head>
                <title>PDF Report</title>
            </head>
            <body>
                <h1>Financial Report</h1>
                <p>Value after rounding: {roundedValue}</p>
            </body>
            </html>";
        // Convert HTML to PDF
        var pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent);
        pdfDocument.SaveAs("Report.pdf");
        Console.WriteLine("PDF generated successfully.");
    }
}
Imports IronPdf
Imports System
Friend Class Program
	Shared Sub Main()
		License.LicenseKey = "License-Key"
		' Create a PDF document
		Dim Renderer = New ChromePdfRenderer()
		' Sample data that might come from a database or computation
		Dim initialValue As Double = 2.345678
		Dim roundedValue As Double = Math.Round(initialValue, 2)
		' HTML content including the rounded value
		Dim htmlContent = $"
            <html>
            <head>
                <title>PDF Report</title>
            </head>
            <body>
                <h1>Financial Report</h1>
                <p>Value after rounding: {roundedValue}</p>
            </body>
            </html>"
		' Convert HTML to PDF
		Dim pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent)
		pdfDocument.SaveAs("Report.pdf")
		Console.WriteLine("PDF generated successfully.")
	End Sub
End Class
VB   C#

C# 四捨五入到小數點後兩位(開發人員如何操作):圖四 - PDF 輸出

這個例子展示了如何結合C#數學運算的精確性和IronPDF的文件生成能力來創建詳細且準確的PDF報告。無論是財務摘要、技術報告,或者任何需要數值準確性的文件,這種方法都將確保您的數據清晰正確地呈現。

結論

C# 四捨五入到小數點後兩位(開發者如何操作):圖 5 - 授權

將數字四捨五入到指定的小數位數是在 C# 中處理小數和雙精度值的基本方面。在本教程中,我們探討了如何使用 Math.Round 函數四捨五入到兩位小數。我們還討論了如何處理數字正好位於可以四捨五入的兩個數字之間的情況。IronPDF 提供了一個 免費試用 供開發人員在購買前探索其功能。如果您確定這是滿足您需求的正確工具,商業用途的授權起價為 $749。

< 上一頁
工廠模式 C#(如何為開發者工作)
下一個 >
C# 子字串(開發者如何運作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >