Rakesh Singh
Rakesh Singh

Reputation: 49

JavaScript US Currency Formatting

The JS function below in JSFiddle Returns ($6.48), however when used in chrome returns -$6.48

function formatCurrency(value) {    
    var neg = false;
    value = parseFloat(value, 10).toFixed(2);
    if (value < 0) {
        neg = true;
        total = Math.abs(value);
    }
    value = value.replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
    return (neg ? '($' + value.replace('-', '') + ')' : '$' + value);
}

alert(formatCurrency("-6.4784"));

I am trying to use a function to format currency at the same time returning the negative values in parentheses.

The simplified version of the code to render the div is like this.

document.getElementById("futureInfo").innerHTML = formatCurrency($(this).find("Variance").text());
<div id="futureInfo"></div>

Upvotes: 0

Views: 480

Answers (1)

Reuel Teodoro
Reuel Teodoro

Reputation: 77

your issue was that you weren't using total variable correctly i changed it to value instead. i also move the toString function so that it make the number into as string so that replace can work properly.

function formatCurrency(value) {
    var neg = false;
    value = parseFloat(value, 10).toFixed(2);
    if (value < 0) {
    neg = true;
    value = Math.abs(value);
    }

    value = value.toString().replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
    return (neg ? ('($-' + value + ')') : ('$' + value));
}

alert(formatCurrency("-6.4784"));

Upvotes: 2

Related Questions