Datatable Number Formatting using Javascript Clientside Callbacks

Hi Dash Community,

I am trying to use number formatting for my dashtable, for specific columns, but done through Javascript clientside callbacks.

I understand how to do this via the usual Python serverside callbacks, using the info on this page Number Formatting | Dash for Python Documentation | Plotly , i.e. from dash_table.Format import Format, Group , and putting the below format argument into the columns dict:

dict(id=‘a’, name=‘Percentage’, type=‘numeric’, format=Format(precision=2, scheme=Scheme.percentage))

But is there any way to do the equivalent in a clientside callback in Javascript, I suppose via the tables columns? I tried to JSON serialise the format objects in Python and pass it through to Javascript via a “Store” component , but that didn’t quite work, all I got was the object reference string serialized e.g. <dash_table.Format.Format object at 0x0000021D9A603CD0>

Thanks
Marcus

Hi All,

This has been resolved.

While I was passing in the right format columns via javascript, because I had some of my number columns rounded using the build in number.toFixed() method, this prevented Dash from formatting the cells correctly. Once I switched to Math.round() JS function, the formatting worked again.

Heads up to anyone else formatting their columns using client callbacks, number.toFixed() prevents column formatting from working.

Thanks
Marcus

It seems like toFixed() is a better solution, but it is not! In some cases it will NOT round correctly. Also, Math.round() will NOT round correctly in some cases.

To correct the rounding problem with the previous Math.round() and toFixed(), you can define a custom JavaScript rounding function that performs a “nearly equal” test to determine whether a fractional value is sufficiently close to a midpoint value to be subject to midpoint rounding. The following function return the value of the given number rounded to the nearest integer accurately.

Number.prototype.roundTo = function(decimal) {
  return +(Math.round(this + "e+" + decimal)  + "e-" + decimal);
}

var num = 9.7654;
console.log( num.roundTo(2)); //output 9.77