Microsoft .NET/C#

[C#] 소수점 자릿수 변경, 소수점 반올림 올림 버림

전자기린 2019. 3. 5. 01:19

string.Format을 이용한 2가지 반올림 방법

//string.Format을 이용한 2가지 반올림 방법
double value = 5.123456789;


//방법1 
string result = string.Format("{0:0.#####0}", value);  
//결과값 result = "5.123457" 
//7번째 자리의 값을 반올림하여 출력.

//방법2 
string result = string.Format("{0:F6}", value); 
//결과값 result = "5.123457" 
//7번째 자리의 값을 반올림하여 출력.
 

Math Class를 이용한 반올림, 올림, 내림

//Math Class를 이용
double value  = 5.123456789;


// 반올림
double result = Math.Round(value, 5);
//결과값 result = "5.12346" 

// 올림
result = Math.Ceiling(value);
//결과값 result = "6" 

// 내림
result = Math.Truncate(value);
//결과값 result = "5"