Reputation: 3125
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?
Upvotes: 2
Views: 4520
Reputation: 26844
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 );
Upvotes: 3
Reputation: 36703
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);
Upvotes: 8