Skip to content

Instantly share code, notes, and snippets.

@afmicc
Created September 21, 2018 01:07
Show Gist options
  • Save afmicc/ed756f24c078b1c66848f0237bb59901 to your computer and use it in GitHub Desktop.
Save afmicc/ed756f24c078b1c66848f0237bb59901 to your computer and use it in GitHub Desktop.
Render function to numeric column type for datatables.net
// usage
$("#dataTable").DataTable(
{
"columns": [
{
"data": "precio",
"name": "Precio",
"render": $.fn.dataTable.render.customNumberFormat('.', ',', 6)
}
]
});
// define format
/* parameters
* thousands: thousand separator, ex: '.'
* decimal: decimal separator, ex: ','
* precision: how many decimals to view, ex: 6
* prefix: add prefix to number, ex: '$'
* postfix: add postfix to number, ex: '$'
*/
$.fn.dataTable.render.customNumberFormat = function (thousands, decimal, precision, prefix, postfix)
{
return function(d)
{
if (typeof d !== 'number' && typeof d !== 'string')
{
return d;
}
var negative = d < 0 ? '-' : '';
var flo = parseFloat(d);
// If NaN then there isn't much formatting that we can do - just
// return immediately, escaping any HTML (this was supposed to
// be a number after all)
if (isNaN(flo))
{
return __htmlEscapeEntities(d);
}
flo = flo.toFixed(precision);
d = Math.abs(flo);
var intPart = parseInt(d, 10);
var floatPart = precision ?
decimal + Number((d - intPart).toFixed(precision)).toString().substring(2) :
'';
return negative + (prefix || '') +
intPart.toString().replace(
/\B(?=(\d{3})+(?!\d))/g, thousands
) +
floatPart +
(postfix || '');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment