I am trying to round the values in my array to 2 decimal points. I understand i can use math.round but will that work for an whole array? Or will i need to write a function to round each value individually.
This is a great time to use map.
// first, let's create a sample array
var sampleArray= [50.2334562, 19.126765, 34.0116677];
// now use map on an inline function expression to replace each element
// we'll convert each element to a string with toFixed()
// and then back to a number with Number()
sampleArray = sampleArray.map(function(each_element){
return Number(each_element.toFixed(2));
});
// and finally, we will print our new array to the console
console.log(sampleArray);
// output:
[50.23, 19.13, 34.01]
So easy! ;)
You can also make use of ES6 syntax
var arr = [1.122,3.2252,645.234234];
arr.map(ele => ele.toFixed(2));
You have to loop through the array. Then, for each element:
<number>.toFixed(2)
method.Math.round(<number>*100)/100
.Comparison of both methods:
Input .toFixed(2) Math.round(Input*100)/100
1.00 "1.00" 1
1.0 "1.00" 1
1 "1.00" 1
0 "0.00" 0
0.1 "0.10" 0.1
0.01 "0.01" 0.01
0.001 "0.00" 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With