简体   繁体   English

将浮点数排序为自然数

[英]sort float numbers as a natural numbers

I have a comma separated float numbers. 我有一个逗号分隔的浮点数。

 var example = "1.1, 1.10, 1.2, 3.1, 3.14, 3.5";

and I want to sort this float numbers like, 我想对这个浮点数进行排序,比如

"1.1, 1.2, 1.10, 3.1, 3.5, 3.14"

actually in my case, the numbers which are after decimals will consider as a natural numbers, so 1.2 will consider as '2' and 1.10 will consider as '10' thats why 1.2 will come first than 1.10. 实际上在我的情况下,小数点后的数字将被视为自然数,因此1.2将被视为'2'而1.10将被视为'10',这就是为什么1.2将首先比1.10更先。

and suggestion or example would be great for me, thanks. 对我来说,建议或例子都很棒,谢谢。

Actually I want to first sort the array on the basis of numbers which are before decimals :) then the above logic will run. 实际上我想先根据小数点前的数字对数组进行排序:)然后运行上面的逻辑。

You can use .sort with custom compare function, like so 你可以使用.sort和自定义比较功能,就像这样

 var example = "1.1, 1.10, 1.2, 3.1, 3.14, 3.5"; var res = example.split(',').sort(function (a, b) { var result; a = a.split('.'), b = b.split('.'); while (a.length) { result = a.shift() - (b.shift() || 0); if (result) { return result; } } return -b.length; }).join(','); console.log(res); 

You need a custom sort function that first compares the numerical value before the decimal point, and then compare the numerical value after the decimal point in case they are equal. 您需要一个自定义排序函数,首先比较小数点之前的数值,然后比较小数点后的数值,以防它们相等。

example.split(", ").sort(function (a, b) {
    var aParts = a.split(".", 2);
    var bParts = b.split(".", 2);
    if (aParts[0] < bParts[0]) return -1;
    if (aParts[0] > bParts[0]) return 1;
    return aParts[1] - bParts[1]; // sort only distinguishes < 0, = 0 or > 0
}).join(", ");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM