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