Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Sorting array of float point numbers

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.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Sorting array of float point numbers

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×