.NET 幫助

C# 將 double 四捨五入為 int(開發人員如何操作)

發佈 2024年4月29日
分享:

在 C# 中將雙精度浮點數四捨五入到整數 在程式設計中,這是一個經常出現的基本任務,尤其是在計算結果為雙精度值但需要整數值進行進一步操作時更為普遍。這個過程包括將可能包含小數位的雙精度值轉換為最接近的整數。這可以通過使用不同的方法來完成,每種方法都遵循指定的四捨五入方式。

在本指南中,我們將探索在C#中將雙精度值四捨五入為整數位所使用的不同策略和函數,幫助開發人員了解每種方法的影響及應用。我們還將探索 IronPDF,這是一個.NET PDF程式庫。

了解 Round 方法

在 C# 中,Math.Round 方法是將 double 值四捨五入到最接近整數的主要工具。這個函數將 double 值四捨五入到最接近的整數值,通過重載提供對四捨五入過程的高度控制,允許指定的小數位數和四捨五入策略。例如,當 double 值恰好位於兩個整數之間的一半時,四捨五入約定決定了該值是向上四捨五入還是向下四捨五入。

以下是一個 Math.Round 方法的基本示例:

public static void Main()
{
    double myDouble = 9.5;
    int myInt = (int)Math.Round(myDouble);
    Console.WriteLine("The rounded integer value is: " + myInt);
}
public static void Main()
{
    double myDouble = 9.5;
    int myInt = (int)Math.Round(myDouble);
    Console.WriteLine("The rounded integer value is: " + myInt);
}
Imports System

Public Shared Sub Main()
	Dim myDouble As Double = 9.5
	Dim myInt As Integer = CInt(Math.Truncate(Math.Round(myDouble)))
	Console.WriteLine("The rounded integer value is: " & myInt)
End Sub
VB   C#

在這段源代碼中,使用 Math.Round 將雙精度值 9.5 四捨五入至最接近的整數。該方法返回 10,因為它四捨五入到最接近的數字。這是將剛好介於兩個整數之間的正數進行四捨五入時的預期結果。

四捨五入和顯式轉換

在 C# 中,將 double 值轉換為整數值的另一種常見方法是通過顯式轉換。顯式轉換涉及將 double 直接強制轉換為 int,這會截斷任何小數位。這意味著它不會四捨五入到最接近的整數,而是到最近的較小整數。當你只需要移除小數位而不考慮最接近的整數值時,這種方法非常有用。

這是執行顯式轉換的方法:

public static void Main()
{
    double myDouble = 9.9;
    int myInt = (int)myDouble;
    Console.WriteLine("The integer value after explicit conversion is: " + myInt);
}
public static void Main()
{
    double myDouble = 9.9;
    int myInt = (int)myDouble;
    Console.WriteLine("The integer value after explicit conversion is: " + myInt);
}
Imports System

Public Shared Sub Main()
	Dim myDouble As Double = 9.9
	Dim myInt As Integer = CInt(Math.Truncate(myDouble))
	Console.WriteLine("The integer value after explicit conversion is: " & myInt)
End Sub
VB   C#

在上面的例子中,輸出結果為 9,因為明確轉換僅僅去掉了 9.9 的小數位,導致較小的整數。這種方法速度快,但在需要根據指定的四捨五入規則進行精確舍入時,可能不合適。

使用其他方法來滿足特定的取整需求

除了 Math.Round 和顯式轉換外,C#還提供其他用於取整 double 值的方法,以滿足不同需求。例如,Math.FloorMath.Ceiling 提供了分別向下取整或向上取整的選項。Math.Floor 對於始終向下取整非常有用,即使是負數值,而 Math.Ceiling 則確保向上取整。

讓我們來看看這些方法的例子:

public static void Main()
{
    double myDouble = 9.2;
    int floorInt = (int)Math.Floor(myDouble);
    int ceilingInt = (int)Math.Ceiling(myDouble);
    Console.WriteLine("Rounded down: " + floorInt);
    Console.WriteLine("Rounded up: " + ceilingInt);
}
public static void Main()
{
    double myDouble = 9.2;
    int floorInt = (int)Math.Floor(myDouble);
    int ceilingInt = (int)Math.Ceiling(myDouble);
    Console.WriteLine("Rounded down: " + floorInt);
    Console.WriteLine("Rounded up: " + ceilingInt);
}
Imports System

Public Shared Sub Main()
	Dim myDouble As Double = 9.2
	Dim floorInt As Integer = CInt(Math.Truncate(Math.Floor(myDouble)))
	Dim ceilingInt As Integer = CInt(Math.Truncate(Math.Ceiling(myDouble)))
	Console.WriteLine("Rounded down: " & floorInt)
	Console.WriteLine("Rounded up: " & ceilingInt)
End Sub
VB   C#

在上面的代碼中,Math.Floor9.2 捨去小數部分變為 9,而 Math.Ceiling 則返回 10,轉向下一個整數。當需要確定無二義性的舍入策略時,這些方法是至關重要的。

IronPDF 介紹

IronPDF 是一個允許C#開發人員創建和管理的 .NET 庫 直接從HTML生成PDF文件. 它使用 Chrome 渲染引擎以確保 PDF 看起來與在網絡瀏覽器中一樣。這使其成為創建基於網頁的報告的完美選擇。IronPDF 可以處理複雜的任務,如添加數位簽章、更改文件佈局以及插入自訂的頁眉、頁腳或浮水印。它易於使用,因為它允許開發者使用熟悉的網頁技術,如 HTML、CSS、JavaScript 和圖像來製作或編輯 PDF 文件。

IronPDF 的主要功能是轉換 HTML轉PDF同時保持佈局和樣式。它可以從各種網頁內容(如報告、發票和文件)生成 PDF,將 HTML 文件、URL 或 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# 的四捨五入功能相結合,開發人員可以將 IronPDF 的 PDF 生成功能與 C# 中的數學運算相結合。這在需要明確且準確呈現數據的財務或報告應用中特別有用。例如,您可以生成發票或財務摘要,其中數字被四捨五入到最接近的整數,以確保可讀性和符合會計標準。

範例代碼

以下是一個示例,說明如何使用IronPDF和C#的Math.Round方法來創建包含四捨五入數據的PDF:

using IronPdf;
using System;
public class PDFGenerationWithRounding
{
    public static void Main()
    {
        License.LicenseKey = "License-Key";
        // Initialize the HTML to PDF renderer
        var renderer = new ChromePdfRenderer();
        // Example data
        double transactionAmount = 123.456;
        int roundedAmount = (int)Math.Round(transactionAmount);
        // HTML content including the rounded amount
        string htmlContent = $@"
            <html>
            <head>
                <title>Transaction Summary</title>
            </head>
            <body>
                <h1>Transaction Details</h1>
                <p>Original Amount: ${transactionAmount}</p>
                <p>Rounded Amount: ${roundedAmount}</p>
            </body>
            </html>";
        // Convert the HTML to a PDF document
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        pdf.SaveAs("TransactionSummary.pdf");
        Console.WriteLine("The PDF document has been generated with rounded figures.");
    }
}
using IronPdf;
using System;
public class PDFGenerationWithRounding
{
    public static void Main()
    {
        License.LicenseKey = "License-Key";
        // Initialize the HTML to PDF renderer
        var renderer = new ChromePdfRenderer();
        // Example data
        double transactionAmount = 123.456;
        int roundedAmount = (int)Math.Round(transactionAmount);
        // HTML content including the rounded amount
        string htmlContent = $@"
            <html>
            <head>
                <title>Transaction Summary</title>
            </head>
            <body>
                <h1>Transaction Details</h1>
                <p>Original Amount: ${transactionAmount}</p>
                <p>Rounded Amount: ${roundedAmount}</p>
            </body>
            </html>";
        // Convert the HTML to a PDF document
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        pdf.SaveAs("TransactionSummary.pdf");
        Console.WriteLine("The PDF document has been generated with rounded figures.");
    }
}
Imports IronPdf
Imports System
Public Class PDFGenerationWithRounding
	Public Shared Sub Main()
		License.LicenseKey = "License-Key"
		' Initialize the HTML to PDF renderer
		Dim renderer = New ChromePdfRenderer()
		' Example data
		Dim transactionAmount As Double = 123.456
		Dim roundedAmount As Integer = CInt(Math.Truncate(Math.Round(transactionAmount)))
		' HTML content including the rounded amount
		Dim htmlContent As String = $"
            <html>
            <head>
                <title>Transaction Summary</title>
            </head>
            <body>
                <h1>Transaction Details</h1>
                <p>Original Amount: ${transactionAmount}</p>
                <p>Rounded Amount: ${roundedAmount}</p>
            </body>
            </html>"
		' Convert the HTML to a PDF document
		Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
		pdf.SaveAs("TransactionSummary.pdf")
		Console.WriteLine("The PDF document has been generated with rounded figures.")
	End Sub
End Class
VB   C#

C# 將 double 四捨五入為 int(如何為開發人員使用):圖 1 - 示例發票 PDF,展示如何使用 Math.round 和 IronPDF 進行數字四捨五入

在此範例中,IronPDF將一個簡單的HTML字串渲染成PDF文件,並包括四捨五入至最接近整數的交易金額的動態數據。這種方法高度適應性,允許開發人員根據他們的具體需求創建更複雜的文檔,過程中精確性和易用性佔據首要地位。

結論

C# 將 double 四捨五入為 int(開發人員指南):圖 2 - IronPDF 授權頁面

在 C# 中將 double 轉換為 int 是一個多用途的過程,會受到 double 值的性質、四捨五入的上下文以及應用程式所需的精度的影響。無論是使用 Math.Round 進行最近整數的四捨五入,顯式轉換進行直接截斷,還是使用 Math.FloorMath.Ceiling 等其他方法進行特定方向的四捨五入,C# 都提供了有效處理 double 值四捨五入的方法。IronPDF 提供了 免費試用 IronPDF的價格從$749起。

< 上一頁
C# 日誌記錄(開發人員的工作原理)
下一個 >
在 C# 中(對開發人員的運作方式)

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

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