Search code examples
javascriptarraystofixed

toFixed() not working well with an array


Why am I not able to use toFixed(2) when doing a console.log of the prices array below? Why is toFixed not working in this instance?

I get the following error: Error: VM1105:8 Uncaught TypeError: prices.toFixed is not a function at <anonymous>:8:20

Here's the simple code:

var prices = [1.23, 48.11, 90.11, 8.50, 9.99, 1.00, 1.10, 67.00];

// your code goes here
prices[0]= 1.99;
prices[2]= 99.99;
prices[6]= 1.95;

console.log(prices.toFixed(2));

When I just print out console.log(prices); I get the following, which is missing the decimals in the actual array. Why is this and how to remedy it?

(8) [1.99, 48.11, 99.99, 8.5, 9.99, 1, 1.95, 67] 

Solution

  • Number#toFixed is a method of Number, not of Array. You need to map all values and apply toFixed on it.

    var prices = [1.23, 48.11, 90.11, 8.50, 9.99, 1.00, 1.10, 67.00];
    
    prices[0]= 1.99;
    prices[2]= 99.99;
    prices[6]= 1.95;
    
    console.log(prices.map(v => v.toFixed(2)));