What is the best way to format table values as currency?

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.

Answer №1

To format numbers as currency in JavaScript, you can use the number.toLocaleString() method along with the optional options argument for specifying the currency and its display.

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

In a practical example, you can gather all table cells that require formatting and apply the formatting using JavaScript:

// Select all elements with class "row_data" and convert them to an array
let cells = Array.prototype.slice.call(document.querySelectorAll(".row_data"));

// Iterate over the array of cells
cells.forEach(function(cell){
  // Convert cell content to a number, format it as currency,
  // and update the cell content with the formatted value
  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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Three pie or doughnut charts instead of one are utilized within Chart.js

Can multiple charts be nested inside one another? To see an example of a single chart and what I would like - where the first one is placed inside the second one and so on - please refer to this js fiddle. var data = [ { label: "title 1", value: ...

Retrieving information through a loop in Next.js

My goal is to utilize the data retrieved from one endpoint to make a call to another endpoint, filtered by ID. I intend to fetch both calls using getServerSideProps and then pass the data to a different component. The initial call will result in an array ...

When the value remains unchanged, Angular's @Input() value does not get updated

Upon running this program, I initially receive the output as false, 5, 500 since they have been initialized in the child component. However, upon clicking the update button, I am unable to revert to the previous values. Instead of getting true, 10, 1000, I ...

The animation using Jquery and CSS is experiencing some glitches on Safari when viewed on an

Why is smooth animation not working on iPad Safari with jQuery animate? $('#myId').css({ 'left': '-100%' }).animate({ 'left': '0' }, 300, 'linear'); I also tried using the addClass option and in ...

Tips for presenting styled HTML content within a dynamic list using HTML and JavaScript

Is there a way to display HTML formatted text within a dynamic list in HTML? I've tried implementing it, but the tags are being displayed instead of the formatted text. Here's an example of the code: <!DOCTYPE html> <html> <body> ...

How come my show and edit routes are not recognizing req.body as defined, unlike my create route?

I recently refactored my code to make it more organized by moving some parts into separate models in my app.js file. However, after doing so, I started encountering errors stating that the items within the req.body object are undefined. Unfortunately, I&ap ...

Employing Bootstrap4 in conjunction with Rails 5

After following the official guide and checking out this post with no success, I'm in need of some help. Can anyone shed some light on this? (source on github) Here is my Gem file: ... #bootstrap gem 'bootstrap', '~> 4.0.0.alpha3.1 ...

Exploring the implementation of if statements within the array map function in the context of Next.js

Is there a way to wrap certain code based on the remainder of the index number being 0? I attempted the following approaches but encountered syntax errors. {index % 3 === 0 ? ... : ...} {index % 3 === 0 && ...} export default function UserPosts() { / ...

Execute identical task using a for loop in JavaScript

Here is a sample code snippet: var seats = [] for (a = 0; a <= seatsNumFront; a++) { seats.push(new Seat((a * xPad) + 300, 60, 30, 30, id++, "A", a, "#998515")) } for (b = 0; b <= seatsNumFront; b++) { seats.push(new Se ...

Capture a snapshot with Protractor using the Jasmine2 Screenshot Reporter

The Protractor configuration file includes 2 custom reporting options: one for logging and the other is the protractor-jasmine2-screenshot-reporter. However, only a blank white screen is displayed when generating a screenshot png. Below is the code snippet ...

What is the best way to add data-content to hr:after using JavaScript?

Adding style to an element in javascript can be simple. For example: myElement.style.color = "red"; However, what if I wanted to achieve something like this: hr:after { content: "myRuntimeValue" } Is there a way to do this using javascript? ...

Container for grid template columns and responsive window in a single row

Imagine having around 250 divs with the class slider-item styled in a certain way. You have a responsive grid in CSS called A which arranges these divs as columns/items when the window resizes, with a minimum item width of 240px. Check out how it looks bel ...

Navigating the intricacies of sub-State mapping in Nuxtjs

I have set up a state called ~/store/modules/general/index.js Within this state, there are Actions named get_info and get_pages, as well as states named info and pages. When I use ...mapActions({ getInfo: 'modules/general/get_info' getPages: ...

What could be the reason for the counter not being incremented when the button is clicked

While attempting to increase the counter in my test, I encountered an issue where pressing the button did not change the value. I tried using both fireEvent from React testing library and React test utils, but the value remained at 10. My project is using ...

Mapping DOM elements to VueJS components for hydration is a key process in facilitating

I have a specific requirement and I am exploring potential solutions using VueJS, as it offers the convenient feature of hydrating pre-rendered HTML from the server. In my Vue components, I do not define a template within the .vue file, but I need them to ...

strange occurrences in localToWorld transformation

Hello there! Currently, I'm working on a project where I'm generating a TextMesh using font geometry and placing it within an empty pivot object. My goal is to obtain the world coordinates of each vertex in the TextMesh so that I can manipulate ...

Vue 3 - Child Component Script Not Updating with Reactive Prop Changes

I am facing an issue where I am trying to pass a reactive data as a prop to a child component in Vue 3. The data updates correctly in the child component's template, but it does not reflect in the child component's script. In the parent component ...

Implementing jQuery during the navigation between Node routes

Below is a snippet of my jQuery code: $(function () { $('.mnav a').click(function () { el = $('.border'); el.addClass('blink'); el.one('webkitAnimationEnd oanimationend msAnimationEnd animatio ...

Tips for choosing a single checkbox from a set of multiple checkboxes in React.js

I iterated through a list of objects to generate table rows, each containing an input tag with the type set as checkbox. const [ isChecked, setIsChecked ] = useState(false); const handleChange = (e) => { setIsChecked(e.target.checked) ...

Assistance with utilizing Regular Expressions to extract the className from a React/JSX component

For instance, I have <img className='class' src='somelink' /> and my goal is to extract only the className='class'. I have already attempted using / className='.+'[ |>] while going through files in search of ...