소수점 반올림 - C#
프로그램/c# fundamental 2009. 2. 25. 17:36 |/// <summary>
/// 반올림 함수
/// </summary>
/// <param name="obj">반올림하고자 하는 값</param>
/// <param name="dgt">표시하고자 하는 소숫점 자리수</param>
/// <returns></returns>
public static string GetFormattedString( object obj, int dgt )
{
double cv = 0;
string dumStr = string.Empty;
int totLen = 2 + dgt;
for( int i = 0; i < dgt; i ++ )
dumStr += "0";
if( obj == null )
return "0." + dumStr;
if( obj is string )
{
if(Convert.ToString(obj as string).Trim() == string.Empty )
{
return "0." + dumStr;
}
cv = double.Parse(Convert.ToString(obj as string).Trim());
}
else if( obj is double )
{
cv = (double)obj;
}
else if( obj is int )
{
cv = (int)obj;
}
else if ( obj is float )
{
cv = (float)obj;
}
// Gets a NumberFormatInfo associated with the en-US culture.
System.Globalization.NumberFormatInfo nfi = new System.Globalization.CultureInfo( "en-US", false ).NumberFormat;
// Displays the same value with four decimal digits.
nfi.NumberDecimalDigits = dgt;
return cv.ToString( "N", nfi );
}