Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array of float point numbers [duplicate]

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?

like image 304
jviotti Avatar asked Aug 28 '13 19:08

jviotti


People also ask

How do you sort an array of floats?

sort(float[] a, int fromIndex, int toIndex) method sorts the specified range of the specified array of floats into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.

How do you sort and remove duplicates in an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

Can array hold duplicate values?

The standard way to find duplicate elements from an array is by using the HashSet data structure. If you remember, Set abstract data type doesn't allow duplicates. You can take advantage of this property to filter duplicate elements.


2 Answers

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.

like image 61
dc5 Avatar answered Sep 26 '22 14:09

dc5


The built in JS sort function treats everything as strings. Try making your own:

var numbers = new Array ( 82.11742562118049, 28.86823689842918, 49.61295450928224, 5.861613903793295 );  function sortFloat(a,b) { return a - b; }  numbers.sort(sortFloat); 
like image 25
Matt Pavelle Avatar answered Sep 24 '22 14:09

Matt Pavelle