This is my code. I want to round the variable element to 2 decimal places. How do I proceed?
computed:{
computedCrypto(){
const element = this.limit ? this.crypto_data.slice(3,this.limit) : this.crypto_data
for (let index = 0; index < element.length; index ) {
console.log(element[index].price_usd.toFixed(2))
}
}
},
}
CodePudding user response:
Your commented out attempt is close, but suffers a few problems mostly to do with variable naming. To keep using a for
loop you need to access the appropriate array, and either mutate or clone and reassign each object (here using spread syntax) while also reassigning each price_usd
value using toFixed(2)
as you were attempting. You'll note that I'm also slice()
ing the crypto_data
array even if there isn't a limit
set in order to avoid mutating the original array.
class Example {
constructor(limit) {
this.crypto_data = [...Array(10).keys()].map(() => ({ price_usd: Math.random() * 10 }));
this.limit = limit ?? 0;
}
computedCrypto() {
const data = this.limit ? this.crypto_data.slice(3, this.limit) : this.crypto_data.slice();
for (let index = 0; index < data.length; index ) {
data[index] = {
...data[index],
price_usd: data[index].price_usd.toFixed(2)
};
}
return data;
}
}
const example = new Example(5);
console.log(example.computedCrypto());
const exampleNoLimit = new Example();
console.log(exampleNoLimit.computedCrypto());
A more succinct version could be written using map()
computedCrypto() {
const data = this.limit
? this.crypto_data.slice(3, this.limit)
: this.crypto_data;
return data.map(o => ({ ...o, price_usd: o.price_usd.toFixed(2) }));
}