我有变量,这是$符号后的负数(实际上它显示带货币符号的货币)。请告诉我如何用货币符号在括号中显示减去货币。我的意思是说如何改变var val =($ 125,220,328.00)
我的代码看起来像这样
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function netAmount(){
var net_amount =0;
$('#productList tr:gt(1)').each(function() {
var row_index= $(this).index();
var qty= $('#productList tr:eq('+row_index+') td input[name="quantity"]').val().replace( /[^0-9\.]/g, '' );
var price= $('#productList tr:eq('+row_index+') td input[name="purchase_price"]').val().replace( /[^0-9\.]/g, '' );
net_amount+= +(parseFloat(qty*price).toFixed(2));
$('input[name="net_ammount"]').val('$'+ addCommas(parseFloat(net_amount).toFixed(2)));
});
}
现在我想如果net_amount看起来像-123225.32那么它在输入[name =“net_ammount”]中显示为($ 123,225.32)
答案 0 :(得分:1)
这是我的工作尝试:
function addCommas(val2) {
val2 = val2.toString(); // cast to a string
// index of minus sign
var negative = val2.indexOf('-');
// org = original index of dot, make val an array; i should be above index of minus + 1; decrease i
for (var i = org = val2.indexOf('.'), val2 = val2.split(""); i > negative + 1; i--) {
// i difference between org and i is multiple of 3 and at the current index is a number
if ((org - i) % 3 == 0 &&
/[0-9]/.test(val2[org - i])) {
// insert a `,` and decrease i
val2.splice(i--, 0, ',');
}
}
val2 = val2.join("");
if(parseInt(val2, 10) >= 0)
return '$' + val2;
else
return '($' + val2 + ')';
}
alert(addCommas(123225.32)); // $123,225.32
alert(addCommas(-123225.32)); // ($123,225.32)
function remCommas(val){
var pre = '';
if(val.indexOf("(") > -1){
pre = "$-";
val = val.replace(/\(\$/, "").replace(/\)/, "");
}
val = pre + val;
return val;
}
alert(remCommas('$123,225.32')); // $123,225.32
alert(remCommas('($123,225.32)')); // $-123,225.32