Sorting HTML Data Doesn't Convert to Float

Sorting HTML Data Doesn't Convert to Float

ofoshoofosho Posts: 5Questions: 0Answers: 0
edited August 2010 in Bug reports
My apologies if this is not a bug, but rather a choice.

I found that when a table contains html data in the td, specifically a div in my case, datatables properly recognizes and removes the tags. However, it then uses a generic (x < y) to sort the string. This caused odd sorting errors in some of my colums. Specifically, numbers in the 1000 and above range where considered smaller than numbers with 3 or less digits. I am not sure why, but the following addition to the sorting function fixed it:

"html-asc": function ( a, b )
{
var x = a.replace( /<.*?>/g, "" ).toLowerCase();
var y = b.replace( /<.*?>/g, "" ).toLowerCase();
if(!isNaN(x))
x = parseFloat(x);
if(!isNaN(y))
y = parseFloat(y);
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
},

"html-desc": function ( a, b )
{
var x = a.replace( /<.*?>/g, "" ).toLowerCase();
var y = b.replace( /<.*?>/g, "" ).toLowerCase();
if(!isNaN(x))
x = parseFloat(x);
if(!isNaN(y))
y = parseFloat(y);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
},

I am sure there is a more efficient, or at least cleaner, way of doing that (perhaps adding an isnum function), but I didn't really want to mess with the code too much.

Again, if this was by choice and I am supposed to make my own sort function for HTML data I apologize.

Thanks,

-O

Replies

  • allanallan Posts: 57,300Questions: 1Answers: 9,127 Site admin
    Your modification looks absolutely find if you want the data inside the HTML to be treated as a float - indeed it is almost identical to this plug-in http://datatables.net/plug-ins/sorting#numbers_html :-). DataTables doesn't do this by default since the inner data can't be assumed to be a floating point number - hence why it is treated as a string.

    Allan
  • ofoshoofosho Posts: 5Questions: 0Answers: 0
    Ahh, I suspected it was too simple of a fix to be a bug. My apologies for not being more thorough in RTFM. Hopefully this will at least avoid someone else from running into this issue.

    Thanks,

    -O
This discussion has been closed.