UNPKG

d3

Version:

A small, free JavaScript library for manipulating documents based on data.

59 lines (51 loc) 1.93 kB
// TODO align, type d3.format = function(specifier) { var match = d3_format_re.exec(specifier), fill = match[1] || " ", sign = match[3] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9]; if (precision) precision = precision.substring(1); if (zfill) { fill = "0"; // TODO align = "="; if (comma) width -= Math.floor((width - 1) / 4); } if (type == "d") precision = "0"; return function(value) { var number = +value, negative = (number < 0) && (number = -number) ? "\u2212" : sign; // Return the empty string for floats formatted as ints. if ((type == "d") && (number % 1)) return ""; // Convert the input value to the desired precision. if (precision) value = number.toFixed(precision); else value = "" + number; // If the fill character is 0, the sign and group is applied after the fill. if (zfill) { var length = value.length + negative.length; if (length < width) value = new Array(width - length + 1).join(fill) + value; if (comma) value = d3_format_group(value); value = negative + value; } // Otherwise (e.g., space-filling), the sign and group is applied before. else { if (comma) value = d3_format_group(value); value = negative + value; var length = value.length; if (length < width) value = new Array(width - length + 1).join(fill) + value; } return value; }; }; // [[fill]align][sign][#][0][width][,][.precision][type] var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/; // Apply comma grouping for thousands. function d3_format_group(value) { var i = value.lastIndexOf("."), f = i >= 0 ? value.substring(i) : (i = value.length, ""), t = []; while (i > 0) t.push(value.substring(i -= 3, i + 3)); return t.reverse().join(",") + f; }