0

Not the best at Javascript and I am still learning, but...

I am trying to calculate the sum of values in a Bootstrap 4 table, and format the output as currency. Currently, I am able to add the numbers with a .toFixed(2) option, but this doesn't give the USD comma format ($#,###.##) that is needed. I need to be able to format both the data within the columns being added and the total result as USD currency.

I have been able to add the values with .toFixed(2) (as I already mentioned) and have attempted using .toLocaleString but that does not have an 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 need the .row_data class values to be summed and output to the .totalRow class, formatted as USD currency. For example, with my code the output would be $11000.00 but I need the output to be $11,000.00.

How can I achieve this?

EDIT: I have read the linked "possible duplicates" and haven't found them to help, but that may be my ignorance when it comes to Javascript. The Regex solution seems like it would work, but I am unsure how to use it within the function.

Drew Johnson
  • 58
  • 1
  • 8
  • @charlieftfl While, it's true that this question has been asked and answered before. I haven't seen anyone answer it as I have below. – Scott Marcus Mar 26 '19 at 20:48

1 Answers1

1

Use: number.toLocaleString() with the optional, options argument object that sets the currency and the currency display.

var number = 123456.789;
console.log(number.toLocaleString('en-US', { style: 'currency', currency: 'USD' }));

So, in your example, we could just gather up all the table cells that need formatting and format them:

// Get all the "row_data" elements into an array
let cells = Array.prototype.slice.call(document.querySelectorAll(".row_data"));

// Loop over the array
cells.forEach(function(cell){
  // Convert cell data to a number, call .toLocaleString()
  // on that number and put result back into the cell
  cell.textContent = (+cell.textContent).toLocaleString('en-US', { style: 'currency', currency: 'USD' });
});
.row_data { text-align:right; font-weight:bold; color:maroon; }
<table id="sum__table">
  <tbody>
    <tr>
      <td>Price 1: </td>
      <td class="row_data">5000.006</td>
      <td>Some more info</td>
    </tr>
    <tr>
      <td>Price 2: </td>
      <td class="row_data">62548000</td>
      <td>Some more info</td>
    </tr>
  </tbody>
</table>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71