Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tablesort.number.js: Support units postfix (enhancement/solved) #201

Open
hbeni opened this issue Jul 14, 2020 · 0 comments
Open

tablesort.number.js: Support units postfix (enhancement/solved) #201

hbeni opened this issue Jul 14, 2020 · 0 comments

Comments

@hbeni
Copy link

hbeni commented Jul 14, 2020

This alternate tablesort.number.js version will recognize units like "1234 m" or "636.64 ft":

// Sort numbers
// Modified version: Also support numbers with units, like "1234 ft"
(function(){
  var cleanNumber = function(i) {
    return i.replace(/[^\-?0-9.]/g, '');
  },

  compareNumber = function(a, b) {
    a = parseFloat(a);
    b = parseFloat(b);

    a = isNaN(a) ? 0 : a;
    b = isNaN(b) ? 0 : b;

    return a - b;
  };

  Tablesort.extend('number', function(item) {
    return item.match(/^[-+]?[£\x24Û¢´€]?\d+\s*([,\.]\d{0,2})/) || // Prefixed currency
      item.match(/^[-+]?\d+\s*([,\.]\d{0,2})?[£\x24Û¢´€]/) || // Suffixed currency
      item.match(/^[-+]?\d+\s*([,\.]\d{0,2})?(?:\s*\w+)/) || // Suffixed unit
      item.match(/^[-+]?(\d)*-?([,\.]){0,1}-?(\d)+([E,e][\-+][\d]+)?%?$/); // Number
  }, function(a, b) {
    a = cleanNumber(a);
    b = cleanNumber(b);

    return compareNumber(b, a);
  });
}());

(Added the line item.match(/^[-+]?\d+\s*([,\.]\d{0,2})?(?:\s*\w+)/) || // Suffixed unit)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant