Sorting array of float point numbers
Problem
I have an Array of float point numbers:
[ 82.11742562118049, 28.86823689842918, 49.61295450928224, 5.861613903793295 ]
After running sort() on the array I get this:
[ 28.86823689842918, 49.61295450928224, 5.861613903793295, 82.11742562118049 ]
Notice how 5.8... is bigger than 49.6... for JavaScript (Node). Why is that?
How can I correctly sort this numbers?
Problem courtesy of: jviotti
Solution
Pass in a sort function:
[….].sort(function(a,b) { return a - b;});
results:
[5.861613903793295, 28.86823689842918, 49.61295450928224, 82.11742562118049]
From MDN:
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order.
Solution courtesy of: dc5
Discussion
View additional discussion.