Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have spliced the data coming from an api to get the first 8 items. How do I convert this spliced data to two decimal places?

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)) 
    }      
  }

  },

    
   
   

     
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) }));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading