跳至頁尾內容
開發者更新

C# Round double to int(對於開發者的運行原理)

在C#中將雙精度浮點數四捨五入到整數 是程式設計中經常出現的一項基本任務,尤其在計算產生雙精度浮點數但需要整數值進行後續操作時非常普遍。 這個過程涉及將可能包含小數位的雙精度浮點值轉換為最接近的整數。 這可以使用多種方法完成,每種方法都符合指定的捨入慣例。

在本指南中,我們將探索在C#中使用的不同策略和函式,以將雙精度浮點值捨入至整數,幫助開發人員理解每種方法的影響和應用。 我們還將探索 IronPDF .NET PDF Library 的功能,它是一個用於在C#中建立PDF文件的強大工具。

理解Round方法

在C#中,Math.Round 方法是將雙精度浮點值捨入至最接近整數的主要工具。 此函式將雙精度浮點值捨入至最接近的整數值,通過允許指定特定數量的小數位數和捨入策略的重載提供了對捨入過程的高度控制。 例如,當雙精度浮點值正好位於兩個整數之間時,捨入慣例決定該值是上捨還是下捨。

這裡是一個 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
$vbLabelText   $csharpLabel

在此源程式碼中,Math.Round 用於將雙精度浮點值 9.5 捨入到最接近的整數。 該方法返回 10,因為它捨入至最接近的數字。 這是在捨入正好位於兩個整數之間的正值時的預期結果。

捨入和顯式轉換

在C#中,將雙精度浮點值轉換為整數值的另一種常見方法是通過顯式轉換。 顯式轉換涉及直接將雙精度浮點數轉換為整數,這將截斷任何小數位。 這意味著它不是捨入到最接近的整數,而是捨入到最接近的小整數。 當您只需刪除小數位而不考慮最接近的整數值時,該方法非常有用。

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

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
$vbLabelText   $csharpLabel

在上面的範例中,輸出將是 9,因為顯式轉換只是簡單地將9.9的部分小數位刪除,導致較小的整數。 此方法很快但在需要根據指定的捨入慣例進行精确捨入時可能不合適。

使用其他方法滿足特定捨入需求

除了 Math.Round 和顯式轉換之外,C#還提供其他方法來捨入雙精度浮點值,以滿足不同的需求。 例如,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
$vbLabelText   $csharpLabel

在上面的程式碼中,Math.Floor9.2 返回 9,捨入至具有更少小數位的最接近數字,而 Math.Ceiling 則返回 10,移動到下一個正整數。 當捨入策略必須偏向於較高或較低的整數值時,這些方法是必不可少的,沒有任何歧義。

IronPDF簡介

探索IronPDF功能 以了解這個 .NET 程式庫如何使 C# 開發人員能夠直接從 HTML 建立和管理 PDF 文件。 它使用 Chrome 渲染引擎來確保 PDF 看起來就像在網頁瀏覽器中的樣子。 這使得用於建立基於網路的報告非常完美。 IronPDF 可以處理複雜的任務,比如新增數位簽名、改變文件佈局、插入自定義的標題、頁尾或浮水印。 它易於使用,因為它允許開發人員使用熟悉的網頁技術,如 HTML、CSS、JavaScript 和影像來製作或編輯 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
$vbLabelText   $csharpLabel

為了將 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
$vbLabelText   $csharpLabel

C# 將雙精度浮點數捨入為整數(如何為開發者工作):圖1 - 使用Math.round和IronPDF顯示四捨五入數字的發票PDF 範例

在此範例中,IronPDF 將簡單的 HTML 字串渲染為 PDF 文件,結合了包含捨入至最接近整數的交易金額的動態資料。 此方法高度適應性,允許開發人員建立更多複雜的、針對其特定需求而定製的文件,精度和易用性是這一過程的重點。

結論

C# 將雙精度浮點數捨入為整數(如何為開發者工作):圖2 - IronPDF 授權頁面

在 C# 中將雙精度浮點數捨入到整數是一個多用途的過程,受到雙精度浮點值的性質、捨入的上下文和應用中的精確性需求的影響。 無論是使用 Math.Round 進行最近整數捨入,還是顯式轉換進行直接截斷,或者像 Math.FloorMath.Ceiling 這樣的方法用於特定捨入方向,C# 提供了有效處理雙精度浮點數捨入的方法。 IronPDF 提供 IronPDF 免費試用,價格從 $999 開始。

常見問題

如何在C#中將double轉換為整數?

在C#中,您可以使用Math.Round方法將double轉換為整數,根據指定的慣例將其四捨五入至最接近的整數,或者通過顯式轉換截斷小數部分。

C#中Math.Floor和Math.Ceiling之間有什麼區別?

在C#中,Math.Floor將double向下舍入至最接近的小整數,而Math.Ceiling將double向上舍入至最接近的大整數。

我如何使用PDF庫在C#中生成PDF文件?

您可以使用IronPDF在C#中生成PDF文件。它允許您使用Chrome渲染引擎將HTML字串、文件或URL轉換成PDF,以實現精確的佈局渲染。

您能提供一個在C#中將double四捨五入為整數並生成PDF的範例嗎?

當然!您可以使用Math.Round將double四捨五入為最接近的整數,並使用IronPDF生成PDF。例如:double myDouble = 12.7; int roundedInt = (int)Math.Round(myDouble);然後使用IronPDF建立包含此整數的PDF。

四捨五入在使用PDF進行財務報告中扮演著什麼角色?

四捨五入在財務報告中至關重要,以確保數值的準確性。IronPDF可以與C#的四捨五入方法整合,使開發者能建立準確表現經過四捨五入後的財務資料的PDF。

顯式轉換如何在C#中處理小數位?

顯式轉換在C#中直接將double轉換為int,截斷小數部分,結果為最接近的小整數。

使用IronPDF進行HTML到PDF轉換的目的何在?

IronPDF用於HTML到PDF轉換,確保輸出的PDF與原始網頁內容非常相似。它使用Chrome渲染引擎來精確渲染佈局,非常適合在C#中生成基於網頁的報告。

什麼時候在C#中應選擇使用Math.Floor而不是Math.Round?

在C#中,需要確保結果總是向下舍入到最接近的小整數時,您會選擇使用Math.Floor,而非根據特定慣例四捨五入至最接近整數的Math.Round

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天。
聊天
電子郵件
給我打電話