Still getting the hang of Javascript, and I'm in the process of learning...
Currently, my challenge involves calculating the total sum of values within a Bootstrap 4 table and formatting the result as currency (specifically in USD format). While I've managed to add up the numbers with the .toFixed(2) option, it doesn't give me the desired comma-separated USD format ($#,###.##). I need guidance on how to properly format both the column data being summed and the final total in USD currency.
Despite trying to use .toFixed(2) for adding values and experimenting with .toLocaleString, I haven't achieved the intended effect.
<table id="sum__table">
<tbody>
<tr>
<td>Some name</td>
<td class="row_data">5000.00</td>
<td>Some more info</td>
</tr>
<tr>
<td>Some Name 2</td>
<td class="row_data">6000.00</td>
<td>Some more info</td>
</tr>
</tbody>
</table>
<div class="totalRow"></div>
<script>
var sum = 0,
sumElements = document.querySelectorAll('#sum__table .row_data');
Array.prototype.forEach.call(sumElements, function (el) {
sum += parseFloat(el.innerText);
});
$('div.totalRow').each(function(el) {
$(this).html("$" + sum.toFixed(2));
});
</script>
I am looking to sum up the values under the .row_data class and display the total in the .totalRow class, formatted as USD currency. Currently, the output is shown as $11000.00
, but I'd like it to appear as $11,000.00
.
Any suggestions on how to achieve this?
EDIT: I have gone through the suggested "possible duplicates," but none seem to address my specific issue. The Regex solution could work, but I'm unsure about implementing it within the function.