I am trying to write a javascript to 3 digit comma separate number values that are passed in through my django database and can't figure it out. Exp: (1000 -> 1,000). Before writing the JS, I am also trying to figure out if I comma separate these values, will they mess up potential usage in other JS code that utilize these numbers to do math? Thanks.
<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, ',');
}
CodePudding user response:
In django templates you can use the intcomma
templatetag to add thousands commas:
${{ s.market_value_of_security|intcomma }}
Then in javascript, you can first use replace
to remove the spaces, commas and $ from the string and then convert the number string into an actual number with parseFloat
:
number = parseFloat(numberText.replace(/[ ,$]/g, ""))