I am making a website where it shows the different currency quotes.
I am consuming an API with FETCH. But I already tried adding.toFix (2) to it and it has not worked for me to show only two numbers after the comma.
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
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
. The solution is as follows:
I've added comments // 1.
// 2.
and // 3.
for the code corresoponding to the above list items
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.