currencyFormat tester

*Handles percentages *Custom currency symbol option *Strips illegal characters *Adds Commas every 3 chars *Rounds pennies by .005

by CommandLineDesign

HTML

<div class="indent">
   <h3>Currency Format Test</h3>
   <div class="indent">
   <div id="formattedNumber"><br /></div><br />
   <input type="text" onChange="testCurrencyFormat(this.value)" />
   </div>
</div>

CSS

.indent{
    margin-left: 20px;
}

JavaScript

function currencyFormat(valueToFormat, currency) {
    if (!valueToFormat) {
        valueToFormat = 0;
    }
    var currencySymbol = '$';
    if (arguments.length > 1) {
        currencySymbol = currency;
    }
    var negativeSymbol = '';
    var percentSymbol = '';
    if (valueToFormat.toString().indexOf('%') > -1 || currencySymbol == '%') {
        percentSymbol = '%';
        currencySymbol = '';
        console.log('valueToFormat '+valueToFormat);
        if (valueToFormat.toString().indexOf('-') > -1) {
            negativeSymbol = '-';
        }
        returnNumber = valueToFormat.replace(/[^0-9.]+/g, '');
    } else {
        if (valueToFormat.toString().indexOf('-') > -1) {
            negativeSymbol = '-';
        }
        var amountArray = valueToFormat.toString().split('.');
        var dollars = Math.abs(amountArray[0].replace(/[^0-9]+/g, ''));
        var dollarsLength = dollars.toString().length;
        if (dollarsLength > 3) {
            dollars = dollars.toString().split('').reverse();
            var commaAccumulator = 0;
            for (var i = 0; i < dollarsLength; i++) {
                if (i % 3 === 0 && i !== 0) {
                    var commaPosition = i + commaAccumulator;
                    dollars.splice(commaPosition, 0, "a");
                    commaAccumulator++;
                }
            }
            dollars = dollars.reverse().join('').replace(/a/g, ",");
        }
        var cents = '00';
        if (amountArray.length > 1) {
            cents = amountArray[1].replace(/[^0-9]+/g, '');
            if (cents.length < 2) {
                cents = cents + '00';
            }
            if (cents.length > 2) {
                cents = cents.split('');
                if (cents[2] > 4) {
                    cents[1]++;
                }
                cents = cents.join('').substring(0, 2);
            }
        }
        returnNumber = dollars + '.' + cents;
    }
    result = negativeSymbol + currencySymbol +...