0

Link to live code.

I'm currently pulling in API data for products that have price points in the thousands. Below, I've tried adding the code toLocaleString() to the price, which in full below is <p id="price">$${product.price?.text.toLocaleString() ?? ""}</p>. However it doesn't seem to add a comma to make the price read in the thousands (example - 1,000).

JS Code

// Fetch Data
async function getData() {
  const res = await fetch(url);
  const data = await res.json();
  let output = "";
  // Loop through first 'groups' array
  data.groups.map(function (group) {
    // Loop through each 'equipments' array
    group.equipments.map((product) => {
      // Define below variable to match cat products only
      const catProducts =
        product["dealer-name"] === "DEALER NAME";
      // If the dealer name is everything but cat products (aka only bfe products)..
      if (!catProducts) {
        // Loop through each 'photos' array
        product.photos.map(() => {
          // Then output the data
          // If year is undefined, replace with empty string
          output += `
            <div class="card">
            <img class="img-fluid" src=${product.photos[0].text} alt=${
            product.model
          } />
            <div class="card--body">
              <h3>${product.year ?? ""} ${product.manufacturer} ${
            product.model ?? ""
          }</h3>
              <p>${product.city ?? "City Not Available"}, ${product.state}</p>
              <p>${product.hours} hours</p>
              <p id="price">$${product.price?.text.toLocaleString() ?? ""}</p> <--- Not working
              <a href='https://used.battlefieldequipment.ca/en/${
                product["group-code"]
              }/${
            product["serial-number"]
          }' class="btn btn-primary">View Details</a>
              </div>
            </div>         
        `;
        });
      }
    });
  });
  // Add to slider
  $(".used-slider").slick("slickAdd", output);
}

getData();

Any idea how I can get the API prices to show up with a comma, making them show properly as thousands numbers?

JD Fill
  • 392
  • 2
  • 7
  • 24
  • this might help: https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – Thallius Sep 23 '21 at 15:24

1 Answers1

2

The number has to be a number rather than a string for that to work. parseFloat(numberAsString).toLocaleString()

misterben
  • 7,455
  • 2
  • 26
  • 47