Bump version to 2.0.1
[dygraphs.git] / gallery / number-format.js
1 /*global Gallery,Dygraph,data */
2 Gallery.register(
3 'number-format',
4 {
5 name: 'Number formatting',
6 setup: function(parent) {
7 parent.innerHTML =
8 "<p>The default formatting mimics printf with %.<i>p</i>g where <i>p</i> is" +
9 " the precision to use. It turns out that JavaScript's toPrecision()" +
10 " method is almost but not exactly equal to %g; they differ for values" +
11 " with small absolute values (10^-1 to 10^-5 or so), with toPrecision()" +
12 " yielding strings that are longer than they should be (i.e. using fixed" +
13 " point where %g would use exponential).</p>" +
14
15 "<p>This test is intended to check that our formatting works properly for a" +
16 " variety of precisions.</p>" +
17
18 "<p>Precision to use (1 to 21):" +
19 " <input type='text' id='p_input' size='20'></p>" +
20 "<p/>" +
21 "<div id='content' style='font-family:Courier New,monospace'></div>";
22 },
23 run: function() {
24 // Helper functions for generating an HTML table for holding the test
25 // results.
26 var createRow = function(columnType, columns) {
27 var row = document.createElement('tr');
28 for (var i = 0; i < columns.length; i ++) {
29 var th = document.createElement(columnType);
30 var text = document.createTextNode(columns[i]);
31 th.appendChild(text);
32 row.appendChild(th);
33 }
34 return row;
35 };
36
37 var createHeaderRow = function(columns) {
38 return createRow('th', columns);
39 };
40
41 var createDataRow = function(columns) {
42 return createRow('td', columns);
43 };
44
45 var createTable = function(headerColumns, dataColumnsList) {
46 var table = document.createElement('table');
47 table.appendChild(createHeaderRow(headerColumns));
48 for (var i = 0; i < dataColumnsList.length; i++) {
49 table.appendChild(createDataRow(dataColumnsList[i]));
50 }
51 return table;
52 };
53
54 var updateTable = function() {
55 var headers = ['Dygraph.floatFormat()', 'toPrecision()',
56 'Dygraph.floatFormat()', 'toPrecision()'];
57 var numbers = [];
58 var p = parseInt(document.getElementById('p_input').value, 10);
59
60 for (var i = -10; i <= 10; i++) {
61 var n = Math.pow(10, i);
62 numbers.push([Dygraph.floatFormat(n, p),
63 n.toPrecision(p),
64 Dygraph.floatFormat(Math.PI * n, p),
65 (Math.PI * n).toPrecision(p)]);
66 }
67
68 // Check exact values of 0.
69 numbers.push([Dygraph.floatFormat(0.0, p),
70 (0.0).toPrecision(p)]);
71
72 var elem = document.getElementById('content');
73 elem.innerHTML = '';
74 elem.appendChild(createTable(headers, numbers));
75 };
76
77 document.getElementById('p_input').value = '4';
78 document.getElementById('p_input').onchange = updateTable;
79 updateTable();
80 }
81 });