排序浮点数的数组[重复]

时间:2021-02-08 17:08:41

This question already has an answer here:

这个问题在这里已有答案:

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:

在数组上运行sort()之后我得到了这个:

[ 28.86823689842918, 49.61295450928224, 5.861613903793295, 82.11742562118049 ]

Notice how 5.8... is bigger than 49.6... for JavaScript (Node). Why is that?

请注意,对于JavaScript(Node),5.8 ...大于49.6 ...这是为什么?

How can I correctly sort this numbers?

我怎样才能正确排序这些数字?

2 个解决方案

#1


32  

Pass in a sort function:

传入排序功能:

[….].sort(function(a,b) { return a - b;});

results:

结果:

[5.861613903793295, 28.86823689842918, 49.61295450928224, 82.11742562118049] 

From MDN:

来自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.

如果未提供compareFunction,则通过将元素转换为字符串并按字典(“词典”或“电话簿”,而不是数字)顺序比较字符串来对元素进行排序。

#2


2  

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

内置的JS排序功能将所有内容视为字符串。尝试制作自己的:

var numbers = new Array ( 82.11742562118049, 28.86823689842918, 49.61295450928224, 5.861613903793295 );

function sortFloat(a,b) { return a - b; }

numbers.sort(sortFloat);

#1


32  

Pass in a sort function:

传入排序功能:

[….].sort(function(a,b) { return a - b;});

results:

结果:

[5.861613903793295, 28.86823689842918, 49.61295450928224, 82.11742562118049] 

From MDN:

来自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.

如果未提供compareFunction,则通过将元素转换为字符串并按字典(“词典”或“电话簿”,而不是数字)顺序比较字符串来对元素进行排序。

#2


2  

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

内置的JS排序功能将所有内容视为字符串。尝试制作自己的:

var numbers = new Array ( 82.11742562118049, 28.86823689842918, 49.61295450928224, 5.861613903793295 );

function sortFloat(a,b) { return a - b; }

numbers.sort(sortFloat);