Samurai Jack
Samurai Jack

Reputation: 3125

Use toFixed() to elements of an array

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

Answers (2)

Eddie
Eddie

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

void
void

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

Related Questions