我正在尝试编写一个javascript到3位逗号单独的数字值,这些值是通过django数据库传入的,但无法计算出来。例:(1000 -> 1,000)。在编写JS之前,我还试图弄清楚如果我用逗号分隔这些值,它们会不会破坏其他利用这些数字进行数学运算的JS代码中的潜在用途?谢谢。
<table class="database-table">
<thead>
<tr>
<th>Market Value</th>
</tr>
</thead>
<tbody>
<tr>
{% for s in securities %}
<tr>
<td id="security-value">${{s.market_value_of_security}}</td>
</tr>
{% endfor %}
</tr>
</tbody>
</table>
<script>
const security_value = document.getElementById("security-value");
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}发布于 2022-08-13 17:45:57
在django模板中,可以使用intcomma模板添加数千个逗号:
${{ s.market_value_of_security|intcomma }}
然后,在javascript中,您可以首先使用replace从字符串中删除空格、逗号和$,然后用parseFloat将数字字符串转换为实际数字。
number = parseFloat(numberText.replace(/[ ,$]/g, ""))
https://stackoverflow.com/questions/73345436
复制相似问题