ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

GetStrMoney

this method is convert integer or float money data to separated comma string that is simple to read

Source

public static string GetStrMoney(this string digit)
{
    string afterPoint = string.Empty;
    string strDigit = digit;
    int pos = digit.IndexOf('.');
    if (digit.IndexOf('.') != -1)
    {
        strDigit = digit.Substring(0, pos);
        afterPoint = digit.Substring(pos, digit.Length - pos);
    }

    int len = strDigit.Length;
    if (len <= 3)
        return digit;

    strDigit = strDigit.ReverseString();
    string result = string.Empty;
    for (int i = 0; i < len; i++)
    {
        result += strDigit[i];
        if ((i + 1) % 3 == 0 && i != len - 1)
            result += ',';
    }

    if (string.IsNullOrEmpty(afterPoint))
        result = result.ReverseString();
    else result = result.ReverseString() + afterPoint;
    return result;
}

public static string ReverseString(this string s)
{
    char[] c = s.ToCharArray();
    string ts = string.Empty;

    for (int i = c.Length - 1; i >= 0; i--)
        ts += c[i].ToString();

    return ts;
}

Example

value in TextBox : 12345
textbox1.text.GetStrMoney() => 12,345

value in TextBox : 1234567.325
textbox1.text.GetStrMoney() => 1,234,567.325

Author: vahid shahbazian

Submitted on: 16 nov 2011

Language: C#

Type: System.String

Views: 5152