I am trying to figure out how to hide the last 12 numbers on price in the button, as it is way to long.
I am using a JSON api, and insertAjacentHTML markup.
This is the code.
`
<script>
fetch('https://free-api.vestige.fi/asset/467518794/price')
.then(res => {
console.log(res);
return res.json();
})
.then(data => {
console.log(data.price);
const markup = `<a>${data.price}</a>`;
document.querySelector('button').insertAdjacentHTML('beforeEnd', markup);
})
.catch(error => console.log(error));
</script>
`
I tried a couple of different methods, but I am just not too great with json and javascript together.
CodePudding user response:
There are built-in methods for numbers in javascript that can help you manipulate those values.
One of them is .toFixed()
, it let's you take a number of digits after the decimal. You can read more about it here.
Here is an example:
const number = 1254.211545
console.log(number.toFixed(4)) // result: 1254.2115
So in your case this code below should work:
<script>
fetch('https://free-api.vestige.fi/asset/467518794/price')
.then(res => {
console.log(res);
return res.json();
})
.then(data => {
console.log(data.price.toFixed(7));
const markup = `<a>${data.price.toFixed(7)}</a>`;
document.querySelector('button').insertAdjacentHTML('beforeEnd', markup);
})
.catch(error => console.log(error));
</script>
Or just, like @Teddy mentioned in the comments, there is also the .substring()
method for strings, you need to convert you number to a string first to use it .toString()
CodePudding user response:
Try convert you number to string then use substring
:
fetch("https://free-api.vestige.fi/asset/467518794/price")
.then((res) => {
console.log(res);
return res.json();
})
.then((data) => {
const numberToString = data.price.toString();
const price = numberToString.substring(0, numberToString.length - 12);
const markup = `<a>${price}</a>`;
document.querySelector("button").insertAdjacentHTML("beforeEnd", markup);
})
.catch((error) => console.log(error));