【问题标题】:display two decimal places with FETCH API使用 FETCH API 显示两位小数
【发布时间】:2021-04-18 02:36:10
【问题描述】:

我正在制作一个显示不同货币报价的网站。

我正在使用 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

【问题讨论】:

  • 你能把你的html截图贴上去吗
  • 你能解释清楚什么是输入,你希望输出如何?

标签: javascript html css api fetch


【解决方案1】:

主要问题是比较号实际上是一个字符串。 第二个问题是它包含一个','所以不能简单地用parseInt解析。 解决方法如下:

  1. 从比较字符串中删除所有逗号
  2. 将字符串解析为int
  3. 将 int 格式化为货币字符串

我添加了 cmets // 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()
&lt;span class="loading"&gt;Loading...&lt;/span&gt;

【讨论】:

    猜你喜欢
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    相关资源
    最近更新 更多