
Math.Round C# (개발자를 위한 작동 방식)
C# 프로그래밍 영역에서 Math.Round 값 메서드는 특히 double-value 및 decimal-value 데이터 유형을 다룰 때 숫자 값을 반올림하는 데 중요한 역할을 합니다. 이 메서드는 주어진 숫자 값을 가장 가까운 정수 값 또는 지정된 소수 자릿수보다 적은 자릿수로 반올림할 수 있게 하여 수학적 연산에서의 유연성과 정밀성을 제공합니다. Midpoint Rounding와 같은 여러 반올림 유형이 가능합니다. 이 기사에서는 Math.Round의 복잡한 부분을 조사하여 C#에서의 다양한 측면 및 사용 시나리오를 탐구할 것입니다. 이 기사의 다음 부분에서는 IronPDF 라이브러리를 사용하여 Iron Software에서 PDF를 처리하는 방법을 살펴볼 것입니다.
Basics of Math.Round in C#
Math.Round 메서드
C#의 Math.Round 메서드는 지정된 반올림 규칙을 사용하여 소수 자릿수 반올림을 위한 강력한 도구입니다. 이는 System 네임스페이스의 일부이며, 다양한 반올림 작업을 수용하기 위해 여러 오버로드를 제공합니다.
// Methods overloaded by Math.Round
Math.Round(Double)
Math.Round(Double, Int32) // Int32 specifies number of fractional digits
Math.Round(Double, Int32, MidpointRounding) // Int32 specifies number of fractional digits, MidpointRounding is the type of rounding method
Math.Round(Double, MidpointRounding) // MidpointRounding is the type of rounding method
Math.Round(Decimal)
Math.Round(Decimal, Int32) // Int32 specifies number of fractional digits
Math.Round(Decimal, Int32, MidpointRounding)
Math.Round(Decimal, MidpointRounding)' Methods overloaded by Math.Round
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Math.Round(Double) Math.Round(Double, Int32) Math.Round(Double, Int32, MidpointRounding) Math.Round(Double, MidpointRounding) Math.Round(Decimal) Math.Round(Decimal, Int32) Math.Round(Decimal, Int32, MidpointRounding) Math.Round(Decimal, MidpointRounding)더블 값 반올림
더블 값을 다룰 때 Math.Round는 일반적으로 숫자를 가장 가까운 정수로 반올림하는 데 사용됩니다. 예를 들어:
double originalValue = 3.75;
double roundedValue = Math.Round(originalValue);
// Output: 4Dim originalValue As Double = 3.75
Dim roundedValue As Double = Math.Round(originalValue)
' Output: 4이 예에서 Math.Round 메서드는 원래의 double 값 3.75를 가장 가까운 정수 값으로 반올림하여 4가 되었습니다.
소수 값 반올림
마찬가지로 Math.Round 메서드는 소수 값에도 적용됩니다. 다음 예를 생각해 보세요.
decimal originalValue = 8.625m;
decimal roundedValue = Math.Round(originalValue, 2);
// Output: 8.63Dim originalValue As Decimal = 8.625D
Dim roundedValue As Decimal = Math.Round(originalValue, 2)
' Output: 8.63여기에서 Math.Round 메서드는 소수 8.625를 두 자리 소수로 반올림하여 결과 값이 8.63이 되도록 합니다.
가장 가까운 정수 값
Math.Round의 주된 목적은 주어진 숫자 값을 가장 가까운 정수로 반올림하는 것입니다. 소수 부분이 정확히 두 정수 사이에 있는 경우 메서드는 지정된 반올림 규칙을 따릅니다. MidpointRounding 열거형은 Math.Round 메서드의 인수로 사용할 수 있으며, 가장 가까운 짝수로 반올림할지 아니면 0에서 벗어나게 반올림할지를 결정합니다.
지정된 반올림 규칙
MidpointRounding 모드를 사용하는 방법을 살펴보겠습니다:
double originalValue = 5.5;
double roundedValueEven = Math.Round(originalValue, MidpointRounding.ToEven);
double roundedValueOdd = Math.Round(originalValue, MidpointRounding.AwayFromZero);
// Output: roundedValueEven = 6, roundedValueOdd = 6Dim originalValue As Double = 5.5
Dim roundedValueEven As Double = Math.Round(originalValue, MidpointRounding.ToEven)
Dim roundedValueOdd As Double = Math.Round(originalValue, MidpointRounding.AwayFromZero)
' Output: roundedValueEven = 6, roundedValueOdd = 6이 예에서 값 5.5를 반올림할 때 MidpointRounding.ToEven은 가장 가까운 짝수로 반올림하여 6을 만들고, MidpointRounding.AwayFromZero는 0에서 벗어나 6을 만듭니다.
지정한 소수 자리 수로 반올림
지정한 소수 위치 수로 숫자를 반올림하려면 Math.Round 메서드는 추가 매개변수로 소수 자릿수를 포함할 수 있습니다:
decimal originalValue = 9.123456m;
decimal roundedValue = Math.Round(originalValue, 3);
// Output: 9.123Dim originalValue As Decimal = 9.123456D
Dim roundedValue As Decimal = Math.Round(originalValue, 3)
' Output: 9.123여기에서 소수 9.123456이 세 자리 소수로 반올림되어 9.123이라는 결과가 나옵니다.
Midpoint Values and Rounding Conventions in C#
중간값은 결과의 가장 적은 유효 자리 다음 값이 두 숫자 사이에 정확히 절반일 때 발생합니다. 예를 들어, 2.56500은 2.57로 두 자리 소수로 반올림할 때의 중간값이며, 3.500은 정수 4로 반올림할 때의 중간값입니다. 명확한 반올림 규칙 없이 중간값을 위한 가장 가까운 값 전략을 식별하는 데 도전이 있다.
C#의 Round 메서드는 중간값을 처리하는 두 가지 반올림 방식을 지원합니다:
-
Zero에서 벗어나는 반올림: 중간 값은 0에서 벗어난 다음 숫자로 반올림됩니다. 이 메서드는 MidpointRounding.AwayFromZero 열거형 멤버로 표시됩니다.
-
가장 가까운 짝수로 반올림 (Banker's Rounding): 중간 값은 가장 가까운 짝수로 반올림됩니다. 이 반올림 방법은 MidpointRounding.ToEven 열거형 멤버로 표시됩니다.
decimal[] decimalSampleValues = { 1.15m, 1.25m, 1.35m, 1.45m, 1.55m, 1.65m };
decimal sum = 0;
// Calculate true mean values.
foreach (var value in decimalSampleValues)
{
sum += value;
}
Console.WriteLine("True mean values: {0:N2}", sum / decimalSampleValues.Length);
// Calculate mean values with rounding away from zero.
sum = 0;
foreach (var value in decimalSampleValues)
{
sum += Math.Round(value, 1, MidpointRounding.AwayFromZero);
}
Console.WriteLine("AwayFromZero mean: {0:N2}", sum / decimalSampleValues.Length);
// Calculate mean values with rounding to the nearest even.
sum = 0;
foreach (var value in decimalSampleValues)
{
sum += Math.Round(value, 1, MidpointRounding.ToEven);
}
Console.WriteLine("ToEven mean: {0:N2}", sum / decimalSampleValues.Length);Dim decimalSampleValues() As Decimal = { 1.15D, 1.25D, 1.35D, 1.45D, 1.55D, 1.65D }
Dim sum As Decimal = 0
' Calculate true mean values.
For Each value In decimalSampleValues
sum += value
Next value
Console.WriteLine("True mean values: {0:N2}", sum / decimalSampleValues.Length)
' Calculate mean values with rounding away from zero.
sum = 0
For Each value In decimalSampleValues
sum += Math.Round(value, 1, MidpointRounding.AwayFromZero)
Next value
Console.WriteLine("AwayFromZero mean: {0:N2}", sum / decimalSampleValues.Length)
' Calculate mean values with rounding to the nearest even.
sum = 0
For Each value In decimalSampleValues
sum += Math.Round(value, 1, MidpointRounding.ToEven)
Next value
Console.WriteLine("ToEven mean: {0:N2}", sum / decimalSampleValues.Length)산출

MidpointRounding 모드

영점 이탈: 1
AwayFromZero 반올림 전략은 두 숫자 사이에서 절반인 숫자를 0에서 멀어지는 가장 가까운 숫자로 반올림합니다.
영점으로: 2
이 전략은 0을 향해 직접적인 반올림이 특징입니다. 결과는 무한히 정확한 결과에 가장 가깝고 크기로 더 크지 않습니다.
짝수로: 0
이 전략은 가장 가까운 숫자로 반올림되며, 두 숫자 사이에서 절반인 숫자는 가장 가까운 짝수로 반올림됩니다.
부(-) 무한대로: 3
이 전략은 아래 방향으로 반올림하며, 결과는 무한히 정확한 결과에 가장 가깝고 크기로 더 크지 않습니다.
정(+) 무한대로: 4
이 전략은 위쪽 방향으로 반올림하며, 결과는 무한히 정확한 결과에 가장 가깝고 크기로 더 작지 않습니다.
정밀도와 더블 정밀도 부동 소수점
정밀도와 더블 값
더블 정밀도 부동 소수점을 사용할 때, 부동 소수점 표현의 특성상 잠재적인 부정확성을 이해하는 것이 필수적입니다. Math.Round 메서드는 값을 가장 가까운 정수 또는 특정 소수 자릿수로 반올림하여 정밀도 문제를 완화합니다.
Math.Round로 지정한 정밀도
개발자는 Math.Round 메서드를 활용하여 계산에서 원하는 정밀도를 달성할 수 있습니다:
double originalValue = 123.456789;
double result = Math.Round(originalValue, 4);
// Output: 123.4568, rounded valueDim originalValue As Double = 123.456789
Dim result As Double = Math.Round(originalValue, 4)
' Output: 123.4568, rounded value이 예에서, 더블 값 123.456789은 네 자리 소수점으로 반올림되어, 더 정밀한 값 123.4568을 얻습니다.
중간점 반올림 전략
중간 값 처리
중간점 반올림 전략은 소수 값이 정확히 두 정수 사이의 절반일 때 중요해집니다. Math.Round 메서드는 지정된 MidpointRounding 전략을 사용하여 이러한 경우를 해결합니다.
중간점 반올림 예시
다음은 중간점 반올림이 사용되는 예입니다:
double originalValue = 7.5;
double roundedValue = Math.Round(originalValue, MidpointRounding.AwayFromZero);
// Output: 8Dim originalValue As Double = 7.5
Dim roundedValue As Double = Math.Round(originalValue, MidpointRounding.AwayFromZero)
' Output: 8여기서 값 7.5는 0에서 벗어나 반올림되어 반올림 값 8을 얻습니다.
실제 시나리오에서의 응용
다양한 상황에서의 적용 예시는 다음과 같습니다:
금융 계산
금융 응용 프로그램에서, 정확한 반올림은 매우 중요합니다. 예를 들어, 금리 계산, 화폐 변환, 또는 세금 계산 시, Math.Round 메서드를 사용하면 결과를 금융 표준에 맞게 적절한 소수 자릿수로 반올림할 수 있습니다.
double interestRate = 0.04567;
double roundedInterest = Math.Round(interestRate, 4); // Round to 4 decimal placesDim interestRate As Double = 0.04567
Dim roundedInterest As Double = Math.Round(interestRate, 4) ' Round to 4 decimal places사용자 인터페이스 표시
사용자 인터페이스에서 숫자 값을 표시할 때, 숫자를 반올림하여 가독성을 높이는 것이 일반적입니다. Math.Round를 사용한 반올림은 제시된 정보의 명확성을 높일 수 있습니다.
double temperature = 23.678;
double roundedTemperature = Math.Round(temperature, 1); // Round to 1 decimal placeDim temperature As Double = 23.678
Dim roundedTemperature As Double = Math.Round(temperature, 1) ' Round to 1 decimal place통계 분석
통계 분석에서는 치우침이나 부정확성을 방지하기 위해 정확한 반올림이 필수적입니다. Math.Round 메서드는 원하는 수준의 정밀도로 결과를 제시에 도움을 줄 수 있습니다.
double meanValue = CalculateMean(data);
double roundedMean = Math.Round(meanValue, 2); // Round mean value to 2 decimal placesDim meanValue As Double = CalculateMean(data)
Dim roundedMean As Double = Math.Round(meanValue, 2) ' Round mean value to 2 decimal places과학적 계산
과학 응용 프로그램에서, 정밀도는 매우 중요합니다. 실험 데이터나 과학적 계산을 할 때, Math.Round를 사용한 반올림은 결과를 의미 있고 정확하게 제시합니다.
double experimentalResult = 9.87654321;
double roundedResult = Math.Round(experimentalResult, 5); // Round to 5 decimal placesDim experimentalResult As Double = 9.87654321
Dim roundedResult As Double = Math.Round(experimentalResult, 5) ' Round to 5 decimal places수학적 모델링
수학적 모델이나 시뮬레이션을 구현할 때, 반올림은 복잡한 계산을 단순화할 수 있습니다. Math.Round 메서드는 모델링 과정에서 중간 결과의 정밀도를 제어하는 데 사용됩니다.
double modelResult = SimulatePhysicalSystem(parameters);
double roundedModelResult = Math.Round(modelResult, 3); // Round to 3 decimal placesDim modelResult As Double = SimulatePhysicalSystem(parameters)
Dim roundedModelResult As Double = Math.Round(modelResult, 3) ' Round to 3 decimal places게임 개발
게임 개발에서 수치적 정확도는 물리 계산, 위치 지정 및 기타 수학적 작업에 매우 중요합니다. Math.Round 메서드는 게임 관련 값을 적절한 정밀도로 반올림하도록 보장합니다.
double playerPosition = CalculatePlayerPosition();
double roundedPosition = Math.Round(playerPosition, 2); // Round to 2 decimal placesDim playerPosition As Double = CalculatePlayerPosition()
Dim roundedPosition As Double = Math.Round(playerPosition, 2) ' Round to 2 decimal places이러한 시나리오 각각에서 Math.Round 메서드는 개발자가 수치 값의 정밀도를 제어하여 응용 프로그램에서 정확성과 가독성을 높일 수 있도록 합니다.
IronPDF 소개합니다
IronPDF의 핵심 기능은 레이아웃과 스타일을 유지하는 HTML을 PDF로 변환하는 것입니다. 웹 콘텐츠를 PDF로 변환하여 보고서, 청구서 및 문서 작성에 적합합니다. HTML 파일, URL 및 HTML 문자열을 PDF로 쉽게 변환할 수 있습니다.
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 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");
// 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");
// 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()
' 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")
' 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")
' 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이제 IronPDF C# PDF 라이브러리를 사용하여 Iron Software에서 PDF 문서를 생성하는 방법을 살펴보겠습니다.
설치
IronPDF는 NuGet 패키지 관리자 콘솔 또는 Visual Studio 패키지 관리자를 통해 설치할 수 있는 옵션을 제공합니다.
NuGet 패키지 관리자를 사용하여 검색창에 "IronPDF"를 입력하여 IronPDF를 설치합니다.
IronPDF를 사용한 PDF 생성
using IronPdf;
List<string> cart = new List<string>();
void AddItems(params string[] items)
{
for (int i = 0; i < items.Length; i++)
{
cart.Add(items[i]);
}
}
Console.WriteLine("Enter the cart items as comma-separated values:");
var itemsString = Console.ReadLine();
if (itemsString != null)
{
var items = itemsString.Split(",").ToArray();
AddItems(items);
}
AddItems("Sample1", "Sample2");
Console.WriteLine("-------------------------------------------------------");
Console.WriteLine("Display Cart");
string name = "Sam";
var count = cart.Count;
string content = $@"
<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} items in the cart.</p>
" + string.Join("\n", cart.Select(x => $"<p>{x}</p>"))
+ @"
</body>
</html>";
var pdfRenderer = new ChromePdfRenderer();
pdfRenderer.RenderHtmlAsPdf(content).SaveAs("cart.pdf");Imports Microsoft.VisualBasic
Imports IronPdf
Private cart As New List(Of String)()
Private Sub AddItems(ParamArray ByVal items() As String)
For i As Integer = 0 To items.Length - 1
cart.Add(items(i))
Next i
End Sub
Console.WriteLine("Enter the cart items as comma-separated values:")
Dim itemsString = Console.ReadLine()
If itemsString IsNot Nothing Then
Dim items = itemsString.Split(",").ToArray()
AddItems(items)
End If
AddItems("Sample1", "Sample2")
Console.WriteLine("-------------------------------------------------------")
Console.WriteLine("Display Cart")
Dim name As String = "Sam"
Dim count = cart.Count
Dim content As String = $"
<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} items in the cart.</p>
" & String.Join(vbLf, cart.Select(Function(x) $"<p>{x}</p>")) & "
</body>
</html>"
Dim pdfRenderer = New ChromePdfRenderer()
pdfRenderer.RenderHtmlAsPdf(content).SaveAs("cart.pdf")위 코드에서 우리는 장바구니 항목의 HTML 문서를 생성하여 IronPDF를 사용하여 PDF 문서로 저장하고 있습니다.
산출

라이센스 (무료 체험 가능)
제공된 코드의 기능을 활성화하려면 라이선스 키를 얻어야 합니다. 체험판 키는 여기에서 얻을 수 있으며, 이는 appsettings.json 파일에 삽입되어야 합니다.
"IronPdf.LicenseKey": "your license key"
체험판 라이선스를 받으려면 이메일 ID를 제공하세요.
결론
결론적으로, C#의 Math.Round 메서드는 double 및 decimal 값을 반올림하는 다재다능한 도구로, 개발자가 가장 가까운 정수 또는 지정된 소수점 자릿수로 반올림할 수 있는 유연성을 제공합니다. 중간값 처리 및 MidpointRounding 전략 사용을 포함한 Math.Round의 세부사항을 이해하는 것은 C# 프로그래밍에서 정확하고 신뢰할 수 있는 수학적 작업에 필수적입니다. 재정 계산, 사용자 인터페이스 표시 또는 정밀한 수치 표현이 필요한 기타 시나리오를 다룰 때 Math.Round 메서드는 프로그래머 툴킷의 필수 자산임이 증명됩니다. 또한 IronPDF가 PDF 문서를 생성하기 위한 다재다능한 라이브러리임을 보았습니다.

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.
관련 기사


