Format Currency //JavaScript Repository

Description

Transforms an input into a monetary field, allowing typing just numbers and also formats the field.
Created: 2005.10.02 - Modified 2013.09.17

Dependencies

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/forms/format-currency [rev. #4]

function formatCurrency(o, n, dig, dec){
    new function(c, dig, dec, m){
        addEvent(o, "keypress", function(e, _){
            if((_ = e.key == 45) || e.key > 47 && e.key < 58){
                var o = this, d = 0, n, s, h = o.value.charAt(0) == "-" ? "-" : "",
                    l = (s = (o.value.replace(/^(-?)0+/g, "$1") + String.fromCharCode(e.key)).replace(/\D/g, "")).length;
                m + 1 && (o.maxLength = m + (d = o.value.length - l + 1));
                if(m + 1 && l >= m && !_) return false;
                l <= (n = c) && (s = new Array(n - l + 2).join("0") + s);
                for(var i = (l = (s = s.split("")).length) - n; (i -= 3) > 0; s[i - 1] += dig);
                n && n < l && (s[l - ++n] += dec);
                _ ? h ? m + 1 && (o.maxLength = m + d) : s[0] = "-" + s[0] : s[0] = h + s[0];
                o.value = s.join("");
            }
            e.key > 30 && e.preventDefault();
        });
    }(!isNaN(n) ? Math.abs(n) : 2, typeof dig != "string" ? "." : dig, typeof dec != "string" ? "," : dec, o.maxLength);
}

Example (Example)

<form name="form" method="post" action="#">
    <fieldset>
    <legend>FormatCurrency</legend>
    <label>2 casas</label>    
    <input type="text" name="a" />
    <label>3 casas</label>    
    <input type="text" name="b" />
    <label>6 casas</label>    
    <input type="text" name="c" />
    </fieldset>
</form>

<script type="text/javascript">
//<![CDATA[
    formatCurrency(document.forms.form.a, 2);
    formatCurrency(document.forms.form.b, 3, " ", "-");
    formatCurrency(document.forms.form.c, 6);
//]]>
</script>

Help

formatCurrency(field: HTMLInput, [floatPoint: Integer = 2], [decimalSep: String = ","], [thousandsSep: String = "."]): String
Formats the input making it assume the behaviour of a monetary field.
field
field that will receive the formatation
floatPoint
amount of decimal places
decimalSep
string that will be used as decimal separator
thousandsSep
string that will be used as thousands separator

Rank (Votes: 120)

3.93