Custom formatter for Google Visualization DataTable
Can be used like a built-in formatters when they are not enough. Define your format with a callback function.
HTML
<script src="https://www.google.com/jsapi"></script>
See <a href="http://stackoverflow.com/questions/7286368/how-to-write-a-custom-formatter-for-google-datatables-for-use-on-visualisation">this</a> stackoverflow post
<br>
<div id="table"></div>
JavaScript
/**
* Custom formatter class for Google Visualization DataTable
* Can be used like a built-in formatters when they are not enough.
* https://developers.google.com/chart/interactive/docs/reference#formatters
* Changes the displayed/formatted value. The value itself remains unchanged.
*
* @param function() custom conversion function
* this function
* - takes one value as input (the original value) and
* - returns the formatted value
*/
var CustomFormatter = function(formatValue) {
this.formatValue = formatValue;
}
/**
* Formats a Google DataTable column
* @param {Object} dt DataTable to format
* @param {Number} column index number
*/
CustomFormatter.prototype.format = function(dt, column) {
for (var i = 0; i < dt.getNumberOfRows(); i++) {
var value = dt.getValue(i, column);
dt.setFormattedValue(i, column, this.formatValue(value));
}
}
google.load('visualization', '1', {
packages: ['table']
});
function drawVisualization() {
// Create and populate the data table.
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('number', 'Seconds');
dataTable.addColumn('number', 'HH:MM:SS');
dataTable.addRow([100, 100]);
dataTable.addRow([1000, 1000]);
dataTable.addRow([3600, 3600]);
dataTable.addRow([10000, 10000]);
dataTable.addRow([10010, 10010]);
dataTable.addRow([10110, 10110]);
dataTable.addRow([11010, 11010]);
dataTable.addRow([11110, 11110]);
// apply built-in formatter
var formatter1 = new google.visualization.BarFormat({width: 120});
formatter1.format(dataTable, 0); // Apply formatter to second column
// define custom formatter
var formatter = new CustomFormatter(function(value) {
var hours = parseInt(value / 3600) % 24;
var minutes = parseInt(value / 60) % 60;
var seconds = value % 60;
return (hours < 10 ? "0" + hours : hours) +
":" + (minutes < 10 ? "0" + minutes : minutes) +
":" + (seconds < 10 ? "0" + seconds : seconds);
});
// apply our...