gpt4 book ai didi

javascript - 添加金额并放入元素

转载 作者:行者123 更新时间:2023-12-02 20:05:52 25 4
gpt4 key购买 nike

我想将两个金额加在一起,每个金额来自不同的元素,然后将它们放入另一个元素中。棘手的部分是将“$”符号和逗号(,)保留在总金额中(或者之后将它们添加到总金额中?)。

有人知道可以做到这一点的 JavaScript 吗?


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Add amounts and put in element</title>
</head>

<body>

<p id="firstAmount">$1,133.79</p>

<p id="secondAmount">$1,900.00</p>

<br />

Total: <p id="totalAmount">$0.00</p>

</body>
</html>



********* *********** 更新 2 **********************

替换:

var total2=addCommasandsign(total);

作者:

var total2=addCommasandsign(total.toFixed(2));


这解决了小数点后零消失的问题。例如,如果您有 $1,133.00 + $1,900.00,您将看到 $3,033
通过此修复,您将看到小数点后的零 => $3,033.00

您可以查看实例here


********* *********** 更新 1 **********************

您可以找到工作代码的实例 here

最佳答案

以下内容应该有效,但未测试:

function addCommasandsign(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;
}

//get html
var firstval=document.getElementById('firstAmount').innerHTML;
var secval=document.getElementById('secondAmount').innerHTML;
//replace $ and , by nothing
firstval=firstval.replace('$','');
firstval=firstval.replace(',','');
secval=firstval.replace('$','');
secval=firstval.replace(',','');
//add values
var total=firstval + secval;
//put , and $ back in place
var total2=addCommasandsign(total);
//insert in html
document.getElementById('totalAmount').innerHTML=total2;

关于javascript - 添加金额并放入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7428973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com