﻿function FormatMoney(strAmount)
{
    var strReturn;
    var intPeriod = (strAmount + "").indexOf(".");

    //format decimals
    if (strAmount != "")
    {
        if (intPeriod == -1)
        {
            strReturn = strAmount + ".00";
        }
        else if (strAmount.length - intPeriod == 1)
        {
            strReturn = strAmount + "00";
        }
        else if (strAmount.length - intPeriod == 2)
        {
            strReturn = strAmount + "0";
        }
        else if (strAmount.length - intPeriod > 3)
        {
            strReturn = FormatMoney(MyRound(parseFloat(strAmount), 2) + "");
        }
        else
        {
            strReturn = strAmount;
        }
    }
    else
    {
        strReturn = "";
    }

    //put in commas if necessary
    if (strReturn.length > 3)
    {
        x = strReturn.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1))
        {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        strReturn = x1 + x2;
    }

    return strReturn;
}

function MyRound(number, X)
{
    return Math.round(number * Math.pow(10, X)) / Math.pow(10, X);
}