출처 : http://csharper.tistory.com/entry/C%EC%9C%BC%EB%A1%9C-%EA%B5%AC%ED%98%84%ED%95%9C-%EB%B0%98%EC%98%AC%EB%A6%BC-Method

 

C# 의 Math.Round 메소드는 반올림 메소드이지만, 사사오입이 아닌 은행원 메소드인가 뭐시기 해서

짝수에 가까워 지게 설계 되어있다.

나는 1.45 를 반올림하면 1.5를 얻고 싶다.

근데 Round 메소드는 1.4 를 준다 ㅠㅠ

대충 돌려보니 이거 맞는거 같다.

 

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);

}

 

Posted by motolies
,