简体   繁体   中英

"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.

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 :)

UPDATE:

Thanks to zer00ne's amazing tip, I was able to refactored the code to make the function work as followed:

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

console.log(avg(nums)); // [ 101, 128, 63 ]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM