简体   繁体   English

使用 FETCH API 显示两位小数

[英]display two decimal places with FETCH API

I am making a website where it shows the different currency quotes.我正在制作一个显示不同货币报价的网站。

I am consuming an API with FETCH.我正在使用带有 FETCH 的 API。 But I already tried adding.toFix (2) to it and it has not worked for me to show only two numbers after the comma.但是我已经尝试向它添加.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(); 

This is my code to currently consume.这是我当前使用的代码。 Where should I make the arrangement?我应该在哪里安排? Does anyone know?有人知道吗? Thank you!谢谢!

... and my html html ...和我的 html html

The main issue is that the compra number is actually a String.主要问题是比较号实际上是一个字符串。 The second issue is that it contains a ',' so it cant be simply parsed with parseInt .第二个问题是它包含一个“,”,因此不能简单地用parseInt解析。 The solution is as follows:解决方法如下:

  1. Remove any commas from the compra string从比较字符串中删除所有逗号
  2. Parse the string as an int将字符串解析为 int
  3. Format the int as a currency string将 int 格式化为货币字符串

I've added comments // 1. // 2. and // 3. for the code corresoponding to the above list items我添加了注释// 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