Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round all the values in an array to 2 decimal points

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.

like image 334
kishan patel Avatar asked Mar 12 '12 16:03

kishan patel


3 Answers

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! ;)

like image 119
Richard Morgan Avatar answered Sep 20 '22 17:09

Richard Morgan


You can also make use of ES6 syntax

var arr = [1.122,3.2252,645.234234];

arr.map(ele => ele.toFixed(2));
like image 26
Atul Parashar Avatar answered Sep 19 '22 17:09

Atul Parashar


You have to loop through the array. Then, for each element:

  • If you want exactely two digits after the comma, use the <number>.toFixed(2) method.
  • Otherwise, use 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
like image 24
Rob W Avatar answered Sep 19 '22 17:09

Rob W