node.js 对浮点数数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18496898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:26:57  来源:igfitidea点击:

Sorting array of float point numbers

javascriptnode.js

提问by jviotti

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?

如何正确排序这些数字?

回答by dc5

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,则通过将元素转换为字符串并按字典顺序(“字典”或“电话簿”,而不是数字)比较字符串来对元素进行排序。

回答by Matt Pavelle

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