using System;
public class 반올림
{
public static void Main(string[] args)
{
double data = 1234.5678;
Console.WriteLine(Math.Round(data, 2));
Console.WriteLine(MyRound(data, 3));
// 반올림할 자리수에 5를 더하고 정수를 곱해 소수 자리를 자른 후
// 다시 실수를 곱하여 실수로 만들어 준다.
// double temp = (int)((data + 0.5) * 1) / 1.0;
// double temp = (int)((data + 0.05) * 10) / 10.0;
double temp = (int)((data + 0.005) * 100) / 100.0;
Console.WriteLine("{0}", temp);
}
/// <summary>
/// 반올림 함수
/// </summary>
/// <param name="num">실수형</param>
/// <param name="pos">자리수</param>
/// <returns></returns>
public static double MyRound(double num, int pos)
{
double result = 0.0;
double half = 0.5;
double factor = 1;
for (int i = 0; i < pos; i++)
{
half *= 0.1;
factor *= 10;
}
result = (int)((num + half) * factor) / (double)factor;
return result;
}
}
- Math.Round
http://msdn.microsoft.com/ko-kr/library/system.math_members(VS.95).aspx
'.Net Project > .Net C#' 카테고리의 다른 글
30장 Random Class(랜덤 클래스) (0) | 2009.08.10 |
---|---|
29장 환경변수 (0) | 2009.08.10 |
27장 Math(수학관련함수) (0) | 2009.08.10 |
26장 파일명추출 (0) | 2009.08.10 |
25장 String Format (0) | 2009.08.10 |