簡體   English   中英

使用 FETCH API 顯示兩位小數

[英]display two decimal places with FETCH API

我正在制作一個顯示不同貨幣報價的網站。

我正在使用帶有 FETCH 的 API。 但是我已經嘗試向它添加.toFix (2) 並且在逗號后只顯示兩個數字對我來說沒有用。

function fetchData() {



fetch("https://www.dolarsi.com/api/api.php?type=valoresprincipales")

  .then(response => {
    return response.json();
  })
  .then(data => {
    const filteredOutput = data.filter(item => {
      switch (item.casa.nombre) {
        case "Dolar Blue":
          return item;
          break;
        default:
          return null;
      }
    })
    let html = "";
    filteredOutput.forEach(item => {

      html += "<p class= \"compra\"><small class= \"compraPrecio\">COMPRA</small><br>  $ " +item.casa.compra + "</p>";
 

    })

    document
      .querySelector('#blueCompra')
      .insertAdjacentHTML("afterbegin", html);
  });
  }
  
  fetchData(); 

這是我當前使用的代碼。 我應該在哪里安排? 有人知道嗎? 謝謝!

...和我的 html html

主要問題是比較號實際上是一個字符串。 第二個問題是它包含一個“,”,因此不能簡單地用parseInt解析。 解決方法如下:

  1. 從比較字符串中刪除所有逗號
  2. 將字符串解析為 int
  3. 將 int 格式化為貨幣字符串

我添加了注釋// 1. // 2.// 3.對應於上述列表項的代碼

 function fetchData () { fetch("https://www.dolarsi.com/api/api.php?type=valoresprincipales").then(response => { return response.json(); }).then(data => { document.querySelector('.loading').remove() const filteredOutput = data.filter(item => { switch (item.casa.nombre) { case "Dolar Blue": return item; break; default: return null; } }) filteredOutput.forEach(item => { let compra = item.casa.compra compra = compra.replace(',', '') // 1. ⭐️ compra = parseInt(compra) // 2. ⭐️ compra = compra.toLocaleString('en-US', { minimumFractionDigits: 2 }) // 3. ⭐️ document.body.innerHTML += '<p><small>COMPRA $' + compra }) }) } fetchData()
 <span class="loading">Loading...</span>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM