Wednesday, April 9, 2014

Format Number as Thousands Currency and Reverse Formate into Numbers in JavaScript

<p id="p1"></p>   

var number = "1234567890.77";

document.getElementById("p1").innerHTML= formatThousands(number);

function formatThousands(number) {

 var number = '' + number;
        var array_n = number.split('.');

        if (array_n.length > 1) {
            var s = array_n[0];
            var d = array_n[1];

            if (array_n[0].length > 3) {
                var i = s.length;
                var r = '';
                var var_2 = i - 3;

                if (s.length > 3) {
                    while ((i -= 3) > 0) {
                        r = ',' + s.substr(i, 3) + r;
                        break;
                    }

                    while ((i -= 2) > 0) {
                        r = ',' + s.substr(i, 2) + r;
                    }

                    return s.substr(0, i + 2) + r + "." + d;
                }
            }
            else {
                return array_n[0] + "." + d;
            }
        }
        else {
            return array_n[0] + "." + "00";
        }
    }

    function reverse_formatThousands(amount) {

        var array_amount = "";
        var array_num = "";

        var var_decimal = "";
        var var_temp_num = "";

        var amount'' + amount;

        array_amount = amount.split(".");

        if (array_amount.length > 1) {
            var_decimal = array_amount[1];

            array_num = array_amount[0].split(",");

            for (var i = 0; i < array_num.length; i++) {
                var_temp_num += array_num[i];
            }
            return (var_temp_num + "." + var_decimal);
        }
        else {
            array_num = array_amount[0].split(",");

            for (var i = 0; i < array_num.length; i++) {
                var_temp_num += array_num[i];
            }

            return var_temp_num;
        }
    }