将浮点数排序为自然数 [英] sort float numbers as a natural numbers

查看:72
本文介绍了将浮点数排序为自然数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用逗号分隔的浮点数.

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"

实际上,在我的情况下,小数点后的数字将被视为自然数,因此1.2将被视为"2",而1.10将被视为"10",这就是为什么1.2优先于1.10的原因.

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.

对我来说,建议或榜样对我来说很好.

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

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

这篇关于将浮点数排序为自然数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆