简体   繁体   English

JavaScript美国货币格式

[英]JavaScript US Currency Formatting

The JS function below in JSFiddle Returns ($6.48), however when used in chrome returns -$6.48 以下JSFiddle中的JS函数返回($ 6.48),但是在chrome中使用时返回-$ 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. 呈现div的代码的简化版本是这样的。

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

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. 我还移动了toString函数,以便将数字转换为字符串,以便replace可以正常工作。

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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM