排序浮点数的数组 [英] Sorting array of float point numbers
本文介绍了排序浮点数的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个浮点数的数组:
I have an array of float point numbers:
[ 82.11742562118049, 28.86823689842918, 49.61295450928224, 5.861613903793295 ]
在数组上运行sort()后我得到:
After running sort() on the array I get this:
[ 28.86823689842918, 49.61295450928224, 5.861613903793295, 82.11742562118049 ]
请注意对于JavaScript(Node),5.8 ...大于49.6 ...为什么会这样?
Notice how 5.8... is bigger than 49.6... for JavaScript (Node). Why is that?
如何正确排序这些数字?
How can I correctly sort this numbers?
推荐答案
传递一个排序函数:
[….].sort(function(a,b) { return a - b;});
结果:
[5.861613903793295, 28.86823689842918, 49.61295450928224, 82.11742562118049]
从MDN :
如果没有提供compareFunction,则通过将元素转换为字符串并按字典(词典或电话簿,而不是数字)顺序比较字符串来对元素进行排序。
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.
这篇关于排序浮点数的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文