d3-format.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // https://d3js.org/d3-format/ v1.4.4 Copyright 2020 Mike Bostock
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5. (global = global || self, factory(global.d3 = global.d3 || {}));
  6. }(this, function (exports) { 'use strict';
  7. // Computes the decimal coefficient and exponent of the specified number x with
  8. // significant digits p, where x is positive and p is in [1, 21] or undefined.
  9. // For example, formatDecimal(1.23) returns ["123", 0].
  10. function formatDecimal(x, p) {
  11. if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
  12. var i, coefficient = x.slice(0, i);
  13. // The string returned by toExponential either has the form \d\.\d+e[-+]\d+
  14. // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
  15. return [
  16. coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
  17. +x.slice(i + 1)
  18. ];
  19. }
  20. function exponent(x) {
  21. return x = formatDecimal(Math.abs(x)), x ? x[1] : NaN;
  22. }
  23. function formatGroup(grouping, thousands) {
  24. return function(value, width) {
  25. var i = value.length,
  26. t = [],
  27. j = 0,
  28. g = grouping[0],
  29. length = 0;
  30. while (i > 0 && g > 0) {
  31. if (length + g + 1 > width) g = Math.max(1, width - length);
  32. t.push(value.substring(i -= g, i + g));
  33. if ((length += g + 1) > width) break;
  34. g = grouping[j = (j + 1) % grouping.length];
  35. }
  36. return t.reverse().join(thousands);
  37. };
  38. }
  39. function formatNumerals(numerals) {
  40. return function(value) {
  41. return value.replace(/[0-9]/g, function(i) {
  42. return numerals[+i];
  43. });
  44. };
  45. }
  46. // [[fill]align][sign][symbol][0][width][,][.precision][~][type]
  47. var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
  48. function formatSpecifier(specifier) {
  49. if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
  50. var match;
  51. return new FormatSpecifier({
  52. fill: match[1],
  53. align: match[2],
  54. sign: match[3],
  55. symbol: match[4],
  56. zero: match[5],
  57. width: match[6],
  58. comma: match[7],
  59. precision: match[8] && match[8].slice(1),
  60. trim: match[9],
  61. type: match[10]
  62. });
  63. }
  64. formatSpecifier.prototype = FormatSpecifier.prototype; // instanceof
  65. function FormatSpecifier(specifier) {
  66. this.fill = specifier.fill === undefined ? " " : specifier.fill + "";
  67. this.align = specifier.align === undefined ? ">" : specifier.align + "";
  68. this.sign = specifier.sign === undefined ? "-" : specifier.sign + "";
  69. this.symbol = specifier.symbol === undefined ? "" : specifier.symbol + "";
  70. this.zero = !!specifier.zero;
  71. this.width = specifier.width === undefined ? undefined : +specifier.width;
  72. this.comma = !!specifier.comma;
  73. this.precision = specifier.precision === undefined ? undefined : +specifier.precision;
  74. this.trim = !!specifier.trim;
  75. this.type = specifier.type === undefined ? "" : specifier.type + "";
  76. }
  77. FormatSpecifier.prototype.toString = function() {
  78. return this.fill
  79. + this.align
  80. + this.sign
  81. + this.symbol
  82. + (this.zero ? "0" : "")
  83. + (this.width === undefined ? "" : Math.max(1, this.width | 0))
  84. + (this.comma ? "," : "")
  85. + (this.precision === undefined ? "" : "." + Math.max(0, this.precision | 0))
  86. + (this.trim ? "~" : "")
  87. + this.type;
  88. };
  89. // Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
  90. function formatTrim(s) {
  91. out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
  92. switch (s[i]) {
  93. case ".": i0 = i1 = i; break;
  94. case "0": if (i0 === 0) i0 = i; i1 = i; break;
  95. default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;
  96. }
  97. }
  98. return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
  99. }
  100. var prefixExponent;
  101. function formatPrefixAuto(x, p) {
  102. var d = formatDecimal(x, p);
  103. if (!d) return x + "";
  104. var coefficient = d[0],
  105. exponent = d[1],
  106. i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
  107. n = coefficient.length;
  108. return i === n ? coefficient
  109. : i > n ? coefficient + new Array(i - n + 1).join("0")
  110. : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
  111. : "0." + new Array(1 - i).join("0") + formatDecimal(x, Math.max(0, p + i - 1))[0]; // less than 1y!
  112. }
  113. function formatRounded(x, p) {
  114. var d = formatDecimal(x, p);
  115. if (!d) return x + "";
  116. var coefficient = d[0],
  117. exponent = d[1];
  118. return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
  119. : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
  120. : coefficient + new Array(exponent - coefficient.length + 2).join("0");
  121. }
  122. var formatTypes = {
  123. "%": function(x, p) { return (x * 100).toFixed(p); },
  124. "b": function(x) { return Math.round(x).toString(2); },
  125. "c": function(x) { return x + ""; },
  126. "d": function(x) { return Math.round(x).toString(10); },
  127. "e": function(x, p) { return x.toExponential(p); },
  128. "f": function(x, p) { return x.toFixed(p); },
  129. "g": function(x, p) { return x.toPrecision(p); },
  130. "o": function(x) { return Math.round(x).toString(8); },
  131. "p": function(x, p) { return formatRounded(x * 100, p); },
  132. "r": formatRounded,
  133. "s": formatPrefixAuto,
  134. "X": function(x) { return Math.round(x).toString(16).toUpperCase(); },
  135. "x": function(x) { return Math.round(x).toString(16); }
  136. };
  137. function identity(x) {
  138. return x;
  139. }
  140. var map = Array.prototype.map,
  141. prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];
  142. function formatLocale(locale) {
  143. var group = locale.grouping === undefined || locale.thousands === undefined ? identity : formatGroup(map.call(locale.grouping, Number), locale.thousands + ""),
  144. currencyPrefix = locale.currency === undefined ? "" : locale.currency[0] + "",
  145. currencySuffix = locale.currency === undefined ? "" : locale.currency[1] + "",
  146. decimal = locale.decimal === undefined ? "." : locale.decimal + "",
  147. numerals = locale.numerals === undefined ? identity : formatNumerals(map.call(locale.numerals, String)),
  148. percent = locale.percent === undefined ? "%" : locale.percent + "",
  149. minus = locale.minus === undefined ? "-" : locale.minus + "",
  150. nan = locale.nan === undefined ? "NaN" : locale.nan + "";
  151. function newFormat(specifier) {
  152. specifier = formatSpecifier(specifier);
  153. var fill = specifier.fill,
  154. align = specifier.align,
  155. sign = specifier.sign,
  156. symbol = specifier.symbol,
  157. zero = specifier.zero,
  158. width = specifier.width,
  159. comma = specifier.comma,
  160. precision = specifier.precision,
  161. trim = specifier.trim,
  162. type = specifier.type;
  163. // The "n" type is an alias for ",g".
  164. if (type === "n") comma = true, type = "g";
  165. // The "" type, and any invalid type, is an alias for ".12~g".
  166. else if (!formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = "g";
  167. // If zero fill is specified, padding goes after sign and before digits.
  168. if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";
  169. // Compute the prefix and suffix.
  170. // For SI-prefix, the suffix is lazily computed.
  171. var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
  172. suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "";
  173. // What format function should we use?
  174. // Is this an integer type?
  175. // Can this type generate exponential notation?
  176. var formatType = formatTypes[type],
  177. maybeSuffix = /[defgprs%]/.test(type);
  178. // Set the default precision if not specified,
  179. // or clamp the specified precision to the supported range.
  180. // For significant precision, it must be in [1, 21].
  181. // For fixed precision, it must be in [0, 20].
  182. precision = precision === undefined ? 6
  183. : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
  184. : Math.max(0, Math.min(20, precision));
  185. function format(value) {
  186. var valuePrefix = prefix,
  187. valueSuffix = suffix,
  188. i, n, c;
  189. if (type === "c") {
  190. valueSuffix = formatType(value) + valueSuffix;
  191. value = "";
  192. } else {
  193. value = +value;
  194. // Determine the sign. -0 is not less than 0, but 1 / -0 is!
  195. var valueNegative = value < 0 || 1 / value < 0;
  196. // Perform the initial formatting.
  197. value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
  198. // Trim insignificant zeros.
  199. if (trim) value = formatTrim(value);
  200. // If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.
  201. if (valueNegative && +value === 0 && sign !== "+") valueNegative = false;
  202. // Compute the prefix and suffix.
  203. valuePrefix = (valueNegative ? (sign === "(" ? sign : minus) : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
  204. valueSuffix = (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
  205. // Break the formatted value into the integer “value” part that can be
  206. // grouped, and fractional or exponential “suffix” part that is not.
  207. if (maybeSuffix) {
  208. i = -1, n = value.length;
  209. while (++i < n) {
  210. if (c = value.charCodeAt(i), 48 > c || c > 57) {
  211. valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
  212. value = value.slice(0, i);
  213. break;
  214. }
  215. }
  216. }
  217. }
  218. // If the fill character is not "0", grouping is applied before padding.
  219. if (comma && !zero) value = group(value, Infinity);
  220. // Compute the padding.
  221. var length = valuePrefix.length + value.length + valueSuffix.length,
  222. padding = length < width ? new Array(width - length + 1).join(fill) : "";
  223. // If the fill character is "0", grouping is applied after padding.
  224. if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
  225. // Reconstruct the final output based on the desired alignment.
  226. switch (align) {
  227. case "<": value = valuePrefix + value + valueSuffix + padding; break;
  228. case "=": value = valuePrefix + padding + value + valueSuffix; break;
  229. case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
  230. default: value = padding + valuePrefix + value + valueSuffix; break;
  231. }
  232. return numerals(value);
  233. }
  234. format.toString = function() {
  235. return specifier + "";
  236. };
  237. return format;
  238. }
  239. function formatPrefix(specifier, value) {
  240. var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)),
  241. e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3,
  242. k = Math.pow(10, -e),
  243. prefix = prefixes[8 + e / 3];
  244. return function(value) {
  245. return f(k * value) + prefix;
  246. };
  247. }
  248. return {
  249. format: newFormat,
  250. formatPrefix: formatPrefix
  251. };
  252. }
  253. var locale;
  254. defaultLocale({
  255. decimal: ".",
  256. thousands: ",",
  257. grouping: [3],
  258. currency: ["$", ""],
  259. minus: "-"
  260. });
  261. function defaultLocale(definition) {
  262. locale = formatLocale(definition);
  263. exports.format = locale.format;
  264. exports.formatPrefix = locale.formatPrefix;
  265. return locale;
  266. }
  267. function precisionFixed(step) {
  268. return Math.max(0, -exponent(Math.abs(step)));
  269. }
  270. function precisionPrefix(step, value) {
  271. return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step)));
  272. }
  273. function precisionRound(step, max) {
  274. step = Math.abs(step), max = Math.abs(max) - step;
  275. return Math.max(0, exponent(max) - exponent(step)) + 1;
  276. }
  277. exports.FormatSpecifier = FormatSpecifier;
  278. exports.formatDefaultLocale = defaultLocale;
  279. exports.formatLocale = formatLocale;
  280. exports.formatSpecifier = formatSpecifier;
  281. exports.precisionFixed = precisionFixed;
  282. exports.precisionPrefix = precisionPrefix;
  283. exports.precisionRound = precisionRound;
  284. Object.defineProperty(exports, '__esModule', { value: true });
  285. }));