Hi @AnnMarieW & @jinnyzor
thanks so much for your input.
I’ve tweaked the code a bit and added proper JS for the base 10 column.
One final (?) question though:
Is it possible to limit the allowed filter options? equals
for instance does not make any sense because due to rounding errors it is impossible to get the correct value in bytes back. Thus limiting the options to >
, <
, and range
is probably enough.
Edit: Forgot to add the code:
assets/dashAgGridFunctions.js
:
var dagfuncs = window.dashAgGridFunctions = window.dashAgGridFunctions || {};
dagfuncs.convertUnits_2 = function(x) {
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
if (isNaN(x)) {
return 'N/A';
} else {
const unitIndex = Math.min(Math.floor(Math.log2(x) / 10), units.length - 1);
const convertedValue = x / (2 ** (10 * unitIndex));
return `${convertedValue.toFixed(2)}${units[unitIndex]}`;
}
}
dagfuncs.convertFilter_2 = () => {
return {
allowedCharPattern: '\\d(.)+\\(?:B|KB|MB|GB|TB|PB)',
numberParser: (text) => {
if (text == null) {
return null;
} else {
const pattern = /(^[0-9.]+)?([KMGTP]?B)$/i;
const match = text.match(pattern);
console.log("convertFilter_2: " + match)
if (match) {
const number = parseFloat(match[1]);
const unit = match[2].toUpperCase();
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
const multiplier = Math.pow(1024, units.indexOf(unit));
return number * multiplier;
} else {
return text;
}
}
}
}
}
dagfuncs.convertFilter_10 = () => {
return {
allowedCharPattern: '\\d(.)+\\(?:B|KB|MB|GB|TB|PB)',
numberParser: (text) => {
if (text == null) {
return null;
} else {
const pattern = /(^[0-9.]+)?([KMGTP]?B)$/i;
const match = text.match(pattern);
console.log("convertFilter_10: " + match)
if (match) {
const number = parseFloat(match[1]);
const unit = match[2].toUpperCase();
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
const multiplier = Math.pow(1000, units.indexOf(unit));
return number * multiplier;
} else {
return text;
}
}
}
}
}
main.py
:
import dash_ag_grid as dag
from dash import Dash, html
import pandas as pd
import numpy as np
app = Dash(__name__)
df = pd.DataFrame(
{"bytes": np.random.randint(0, 10000000000, size=5000)}
)
grid = dag.AgGrid(
rowData=df.to_dict("records"),
columnDefs=[
{
"field": "bytes",
"headerName": "Bytes"
},
{
"field": "bytes",
"headerName": "Bytes-base_10",
"valueFormatter": {"function": "d3.format('(.2s')(params.value)"},
"filterParams": {'function': 'convertFilter_10()'}
},
{
"field": "bytes",
"headerName": "Bytes-base_2",
"valueFormatter": {"function": "convertUnits_2(params.value)"},
"filterParams": {'function': 'convertFilter_2()'}
}
],
defaultColDef={
"sortable": True,
"filter": "agNumberColumnFilter"
},
dashGridOptions={"enableCellTextSelection": True}
)
app.layout = html.Div(grid)
if __name__ == "__main__":
app.run_server(debug=True)