Javascript 获取小计、应用折扣并显示新金额

Javascript 获取小计、应用折扣并显示新金额,javascript,jquery,Javascript,Jquery,我有下面的代码,但当美元金额有逗号时,我会遇到问题,例如$1234.56。当我使用下面的代码时,它会吐出0.00。如果超过1000,则应使用逗号显示新的小计 var subtotal = $('.divWithAmount').text().replace("$",""); // Get the subtotal amount and remove the dollar sign var discount = subtotal * 0.2; // Multiply the amount by 2

我有下面的代码,但当美元金额有逗号时,我会遇到问题,例如$1234.56。当我使用下面的代码时,它会吐出0.00。如果超过1000,则应使用逗号显示新的小计

var subtotal = $('.divWithAmount').text().replace("$",""); // Get the subtotal amount and remove the dollar sign
var discount = subtotal * 0.2; // Multiply the amount by 20%
var newSub = subtotal - discount; // Calculate the new subtotal
var newSubtotal = newSub.toFixed(2); // Show only the last two numbers after the decimal
console.log(newSubtotal);

谢谢你的帮助

它不起作用的主要原因是
$('.divWithAmount').text()返回的值属于
字符串类型

要执行操作,它需要是一个数字,要启用它,您还需要删除逗号,然后使用例如
parseFloat()
对其进行解析

var subtotal=parseFloat($('div').text().replace(“$”,”).replace(“,”,”);
var折扣=小计*0.2;//将金额乘以20%
var newSub=小计-折扣;//计算新的小计
var newSubtotal=newSub.toFixed(2);//仅显示小数点后的最后两个数字
log(parseFloat(newSubtotal.toLocaleString())


$51234.56
要从字符串值中提取数字,请执行以下操作

var amount = "$1,234.56";
var doublenumber = Number(amount.replace(/[^0-9\.]+/g,""));

一旦您获得编号,您就可以执行您想要的操作,它将解决您面临的问题。

您是否尝试删除$和逗号?我确实尝试了下面的LGson建议,但如果我可以添加回逗号,那就太好了如果newSubtotal的值超过1000。我建议您尝试使用数字类型并借助正则表达式的更新方法…parseFloat(“123456789012345.229”)将返回123456789012345.23 parseFloat(“123456789012345.203”)将返回123456789012345.2。。因此,如果div中的金额是,例如,80234.56美元,那么newSubtotal的新金额是64187.65美元。是否有需要更新的内容以便添加回逗号($64187.65)?@user2428993,对于添加逗号,显然有一个内置函数this@user2428993更新了我的答案。