Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Math.round" is not rounding to the nearest integer correctly

Can someone please kindly explain to me why "Math.round" is not rounding to the nearest integer correctly? I have a 2D array, in which I want to find out the average of each columns.

const nums = [[ 20,10,35 ],[70,179,30],[207,223,8],[38,53,52],[234,209,251],[35,94,2]]

After transposing the each columns into rows:

[
  [ 20, 70, 207, 38, 234, 35 ],
  [ 10, 179, 223, 53, 209, 94 ],
  [ 35, 30, 8, 52, 251, 2 ]
]

I was able to return the average to be rounded off.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const avg = (arr) => arr[0].map((_,i) => arr.reduce((sum,v) => sum + Math.round(v[i]/arr.length),0))

Unfortunately, "Math.round" is not rounding the result correctly:

before  // [ 100.66666666666667, 127.99999999999999, 63.00000000000001 ]
after   // [ 101, 129, 63 ]

As you can see the 2nd element shoud have rouned off to "128" instead of "129". I’ve tried testing as followed without problem:

console.log(Math.round(127.99999999999999)); // 128

However, "Math.round" from my function is outputting incorrect result. Is this a glitch? Or is there something wrong with my function? Any feedback will be greatly appreciated, million thanks in advance 🙂

>Solution :

JavaScript math is at times inaccurate because it stores numbers in memory as binary floats, for details see Why JavaScript is Bad At Math. Anyways, if you’re looking to have an array of three averages see the example below.

const data = [
  [ 20, 70, 207, 38, 234, 35 ],
  [ 10, 179, 223, 53, 209, 94 ],
  [ 35, 30, 8, 52, 251, 2 ]
];

let output = data.map(sub => Math.round(
  sub.reduce(
    (sum, cur) => sum + cur)/sub.length)
);

console.log(output);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading