Sorting array of float point numbers
本问题已经有最佳答案,请猛点这里访问。
我有一个浮点数数组:
1 | [ 82.11742562118049, 28.86823689842918, 49.61295450928224, 5.861613903793295 ] |
在数组上运行sort()之后,我得到:
1 | [ 28.86823689842918, 49.61295450928224, 5.861613903793295, 82.11742562118049 ] |
号
注意5.8…大于49.6…对于javascript(节点)。为什么?
如何正确排序这些数字?
传递排序函数:
1 | [….].sort(function(a,b) { return a - b;}); |
结果:
1 | [5.861613903793295, 28.86823689842918, 49.61295450928224, 82.11742562118049] |
号
从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.
号
内置的JS sort函数将所有内容视为字符串。尝试自己制作:
1 2 3 4 5 | var numbers = new Array ( 82.11742562118049, 28.86823689842918, 49.61295450928224, 5.861613903793295 ); function sortFloat(a,b) { return a - b; } numbers.sort(sortFloat); |