Currency Sorting Algorithm Bugged on Null Data Values

Currency Sorting Algorithm Bugged on Null Data Values

adamterlsonadamterlson Posts: 4Questions: 0Answers: 0
edited July 2011 in Bug reports
The logic as it's posted (given below for reference) bombs on null data. The issue is that the null data makes the local X and Y variables get assigned to [0], while the next block of code attempts to run ".substring" against it. This will obviously fail.

Here is a new version that works. I additionally added handling for null data (which could be removed if desired, but I needed it):

[code]
jQuery.fn.dataTableExt.oSort['currency-asc'] = function (a, b)
{
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
var x = (a == "-" || a == "") ? 0 : a.replace(/,/g, "").substring(1); //Doesn't call .substring when it's null data.
var y = (b == "-" || b == "") ? 0 : b.replace(/,/g, "").substring(1);

/* Parse and return */
x = parseFloat(x);
y = parseFloat(y);
return x - y;
};

jQuery.fn.dataTableExt.oSort['currency-desc'] = function (a, b)
{
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
var x = (a == "-" || a == "") ? 0 : a.replace(/,/g, "").substring(1);
var y = (b == "-" || b == "") ? 0 : b.replace(/,/g, "").substring(1);

/* Parse and return */
x = parseFloat(x);
y = parseFloat(y);
return y - x;
};
[/code]

Here is the old version for reference:

[code]
jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) {
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
var x = a == "-" ? 0 : a.replace( /,/g, "" );
var y = b == "-" ? 0 : b.replace( /,/g, "" );

/* Remove the currency sign */
x = x.substring( 1 ); //Bombs -- Cannot call .substring on a number.
y = y.substring( 1 ); //Bombs -- Cannot call .substring on a number.

/* Parse and return */
x = parseFloat( x );
y = parseFloat( y );
return x - y;
};

jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) {
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
var x = a == "-" ? 0 : a.replace( /,/g, "" );
var y = b == "-" ? 0 : b.replace( /,/g, "" );

/* Remove the currency sign */
x = x.substring( 1 ); //Bombs -- Cannot call .substring on a number.
y = y.substring( 1 ); //Bombs -- Cannot call .substring on a number.

/* Parse and return */
x = parseFloat( x );
y = parseFloat( y );
return y - x;
};

[/code]

Replies

  • allanallan Posts: 63,382Questions: 1Answers: 10,449 Site admin
    When you say null data, you mean an empty string? It looks like the above code would probably still give an error on a null.

    Allan
  • adamterlsonadamterlson Posts: 4Questions: 0Answers: 0
    Yes, sorry, I mean "empty" cells. I'm not sure that it's even possible to get null into this function?
  • victorovictoro Posts: 5Questions: 0Answers: 0
    Thanks Adam, worked like a charm.
This discussion has been closed.