2

I have an array containing numerical values like this:

myArray = [432.2309012, 4.03852, 6546.46756];

I want to have maximum 2 digits after the dot so I use toFixed(2):

myArray.forEach(a => a.toFixed(2));

The result that is returned is undefined. Is something wrong?

Samurai Jack
  • 2,985
  • 8
  • 35
  • 58

2 Answers2

8

You are not setting the value back. For each just iterates over the array and does not return anything. Use .map instead.

myArray = [432.2309012, 4.03852, 6546.46756];
myArray = myArray.map(a => a.toFixed(2));
console.log(myArray);
void
  • 36,090
  • 8
  • 62
  • 107
3

forEach does not return any value and that is the reason why you are getting undefined. Use map instead

let myArray = [432.2309012, 4.03852, 6546.46756];
let result = myArray.map(a => a.toFixed(2));

console.log( result );

For more info, you can check doc of map


If you really want to use forEach, you have to push each value to an array

let myArray = [432.2309012, 4.03852, 6546.46756];
let result = [];
 
myArray.forEach(a => result.push( a.toFixed(2) ));

console.log( result );
Eddie
  • 26,593
  • 6
  • 36
  • 58