index.html 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. <!doctype html>
  2. <html lang="en" class="no-js">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>accounting.js: JavaScript number and currency formatting library</title>
  6. <link href="demo-resources/style.css" rel="stylesheet"/>
  7. <link rel="canonical" href="http://openexchangerates.github.io/accounting.js/" />
  8. <script type="text/javascript">
  9. var _gaq = _gaq || [];
  10. _gaq.push(['_setAccount', 'UA-17884149-3']);
  11. _gaq.push(['_trackPageview']);
  12. (function() {
  13. var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  14. ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  15. var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  16. })();
  17. </script>
  18. </head>
  19. <body>
  20. <section>
  21. <h1>accounting.js</h1>
  22. <p><strong>accounting.js</strong> is a tiny JavaScript library by <a href="https://openexchangerates.org" title="Open Exchange Rates free currency data API" target="_blank">Open Exchange Rates</a>, providing simple and advanced number, money and currency formatting.</p>
  23. <p>Features custom output formats, parsing/unformatting of numbers, easy localisation and spreadsheet-style column formatting (to line up symbols and decimals).</p>
  24. <p>It's lightweight, has no dependencies and is suitable for all client-side and server-side JavaScript applications.</p>
  25. <p><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="josscrowcroft" data-url="http://openexchangerates.github.io/accounting.js" data-text="accounting.js - JavaScript library for money/currency formatting">Tweet</a> &nbsp; <g:plusone size="medium"></g:plusone></p>
  26. <ul>
  27. <li><a href="#methods" title="library methods overvew">methods &amp; examples</a>
  28. <li><a href="#demo" title="demo">demo</a>
  29. <li><a href="#instructions" title="instructions">instructions</a>
  30. <li><a href="#documentation" title="documentation">documentation</a>
  31. <li><a href="#roadmap" title="roadmap">roadmap</a>
  32. <li><a href="#support" title="support">feedback / support</a>
  33. <li><a href="#download" title="download">download</a>
  34. <li><a href="#links" title="links">links</a>
  35. </ul>
  36. </section>
  37. <section id="methods">
  38. <h2>Library Methods</h2>
  39. <h4><strong>formatMoney()</strong> - format any number into currency</h4>
  40. <p>The most basic library function for formatting numbers as money values, with customisable currency symbol, precision (decimal places), and thousand/decimal separators:</p>
  41. <pre class="prettyprint lang-js">// Default usage:
  42. accounting.formatMoney(12345678); // $12,345,678.00
  43. // European formatting (custom symbol and separators), can also use options object as second parameter:
  44. accounting.formatMoney(4999.99, "&euro;", 2, ".", ","); // &euro;4.999,99
  45. // Negative values can be formatted nicely:
  46. accounting.formatMoney(-500000, "&pound; ", 0); // &pound; -500,000
  47. // Simple `format` string allows control of symbol position (%v = value, %s = symbol):
  48. accounting.formatMoney(5318008, { symbol: "GBP", format: "%v %s" }); // 5,318,008.00 GBP</pre>
  49. <h4><strong>formatColumn()</strong> - format a list of values for column-display</h4>
  50. <p>This table demonstrates how <strong>accounting.js</strong> can take a list of numbers and money-format them with padding to line up currency symbols and decimal places</p>
  51. <p>In order for the padded spaces to render correctly, the containing element must be CSS styled with <code>white-space: pre</code> (pre-formatted) - otherwise the browser will squash them into single spaces.</p>
  52. <table id="demo-table">
  53. <thead>
  54. <tr>
  55. <th>Original Number:</th>
  56. <th>With accounting.js:</th>
  57. <th>Different settings:</th>
  58. <th>European format:</th>
  59. <th>Symbol after value:</th>
  60. </tr>
  61. </thead>
  62. <tbody></tbody>
  63. </table>
  64. <pre class="prettyprint lang-js">// Format list of numbers for display:
  65. accounting.formatColumn([123.5, 3456.49, 777888.99, 12345678, -5432], "$ ");</pre>
  66. <h4><strong>formatNumber()</strong> - format a number with custom precision and localisation</h4>
  67. <p>The base function of the library, which takes any number or array of numbers, runs <code>accounting.unformat()</code> to remove any formatting, and returns the number(s) formatted with separated thousands and custom precision:</p>
  68. <pre class="prettyprint lang-js">accounting.formatNumber(5318008); // 5,318,008
  69. accounting.formatNumber(9876543.21, 3, " "); // 9 876 543.210</pre>
  70. <h4><strong>toFixed()</strong> - better rounding for floating point numbers</h4>
  71. <p>Implementation of toFixed() that treats floats more like decimal values than binary, fixing inconsistent precision rounding in JavaScript (where some .05 values round up, while others round down):</p>
  72. <pre class="prettyprint lang-js">(0.615).toFixed(2); // "0.61"
  73. accounting.toFixed(0.615, 2); // "0.62"</pre>
  74. <h4><strong>unformat()</strong> - parse a value from any formatted number/currency string</h4>
  75. <p>Takes any number and removes all currency formatting. Aliased as <code>accounting.parse()</code></p>
  76. <pre class="prettyprint lang-js">accounting.unformat("&pound; 12,345,678.90 GBP"); // 12345678.9</pre>
  77. </section>
  78. <section id="demo">
  79. <h2>Demo / Try it out</h2>
  80. <h4>Money formatting:</h4>
  81. <div class="well">
  82. <p>Enter any number into the box and choose currency. Uses <code>accounting.formatMoney()</code>:</p>
  83. <p>
  84. <select id="demo-number-symbol">
  85. <option value="$ ">$</option>
  86. <option value="&pound; ">&pound;</option>
  87. <option value="HK$ ">HK$</option>
  88. <option data-locale="european" value="&euro; ">&euro; </option>
  89. </select>
  90. <input type="text" maxlength="20" class="" id="demo-number-value" value="" />
  91. </p>
  92. <p>Result: <strong><span id="demo-number-result">$ 0.00</span></strong></p>
  93. </div>
  94. <h4>Column formatting:</h4>
  95. <div class="well">
  96. <p>Edit the values in the table to see how <strong>formatColumn()</strong> keeps them aligned:</p>
  97. <table id="demo-column">
  98. <tbody>
  99. <tr>
  100. <td><input type="text" value="1000000" maxlength="20" /></td>
  101. <td class="output">$ 1,000,000.00</td>
  102. <td class="output2">GBP 1,000,000</td>
  103. </tr>
  104. <tr>
  105. <td><input type="text" value="-5000" maxlength="20" /></td>
  106. <td class="output">$ -5,000.00</td>
  107. <td class="output2">GBP (5,000)</td>
  108. </tr>
  109. <tr>
  110. <td><input type="text" value="0" maxlength="20" /></td>
  111. <td class="output">$ 0.00</td>
  112. <td class="output2">GBP --</td>
  113. </tr>
  114. </tbody>
  115. </table>
  116. </div>
  117. </section>
  118. <section id="instructions">
  119. <h2>Basic Instructions:</h2>
  120. <p>1. Download the script and put it somewhere, then reference it in your HTML like so:</p>
  121. <pre class="prettyprint">&lt;script src=&quot;path/to/accounting.js&quot;&gt;&lt;/script&gt;
  122. &lt;script type=&quot;text/javascript&quot;&gt;
  123. // Library ready to use:
  124. accounting.formatMoney(5318008);
  125. &lt;/script&gt;</pre>
  126. <p>2. See the documentation and source-code for full method/parameter information.</p>
  127. </section>
  128. <section id="documentation">
  129. <h2>Documentation</h2>
  130. <p>Information on the parameters of each method. See <a href="#methods" title="accounting.js library methods">library methods</a> above for more examples. Optional parameters are in <code><em>[italics]</em></code>, with the default value indicated.</p>
  131. <h4><strong>accounting.settings</strong></h4>
  132. <pre class="prettyprint lang-js">// Settings object that controls default parameters for library methods:
  133. accounting.settings = {
  134. currency: {
  135. symbol : "$", // default currency symbol is '$'
  136. format: "%s%v", // controls output: %s = symbol, %v = value/number (can be object: see below)
  137. decimal : ".", // decimal point separator
  138. thousand: ",", // thousands separator
  139. precision : 2 // decimal places
  140. },
  141. number: {
  142. precision : 0, // default precision on numbers is 0
  143. thousand: ",",
  144. decimal : "."
  145. }
  146. }
  147. // These can be changed externally to edit the library's defaults:
  148. accounting.settings.currency.format = "%s %v";
  149. // Format can be an object, with `pos`, `neg` and `zero`:
  150. accounting.settings.currency.format = {
  151. pos : "%s %v", // for positive values, eg. "$ 1.00" (required)
  152. neg : "%s (%v)", // for negative values, eg. "$ (1.00)" <em>[optional]</em>
  153. zero: "%s -- " // for zero values, eg. "$ --" <em>[optional]</em>
  154. };
  155. // Example using underscore.js - extend default settings (also works with $.extend in jQuery):
  156. accounting.settings.number = _.defaults({
  157. precision: 2,
  158. thousand: " "
  159. }, accounting.settings.number);</pre>
  160. <h4><strong>accounting.formatMoney()</strong></h4>
  161. <pre class="prettyprint lang-js">// Standard usage and parameters (returns string):
  162. accounting.formatMoney(number<em>,[symbol = "$"],[precision = 2],[thousand = ","],[decimal = "."],[format = "%s%v"]</em>)
  163. // Second parameter can be an object:
  164. accounting.formatMoney(number<em>, [options]</em>)
  165. // Available fields in options object, matching `settings.currency`:
  166. var options = {
  167. symbol : "$",
  168. decimal : ".",
  169. thousand: ",",
  170. precision : 2,
  171. format: "%s%v"
  172. };
  173. // Example usage:
  174. accounting.formatMoney(12345678); // $12,345,678.00
  175. accounting.formatMoney(4999.99, "&euro;", 2, ".", ","); // &euro;4.999,99
  176. accounting.formatMoney(-500000, "&pound; ", 0); // &pound; -500,000
  177. // Example usage with options object:
  178. accounting.formatMoney(5318008, {
  179. symbol: "GBP",
  180. precision: 0,
  181. thousand: "&middot",
  182. format: {
  183. pos : "%s %v",
  184. neg : "%s (%v)",
  185. zero: "%s --"
  186. }
  187. });
  188. // Will recursively format an array of values:
  189. accounting.formatMoney([123, 456, [78, 9]], "$", 0); // ["$123", "$456", ["$78", "$9"]]</pre>
  190. <h4><strong>accounting.formatColumn()</strong></h4>
  191. <pre class="prettyprint lang-js">// Standard usage and parameters (returns array):
  192. accounting.formatColumn(list<em>, [symbol = "$"],[precision = 2],[thousand = ","],[decimal = "."],[format = "%s%v"]</em>)
  193. // Second parameter can be an object (see formatNumber for available options):
  194. accounting.formatColumn(list, <em>[options]</em>)
  195. // Example usage (NB. use a space after the symbol to add arbitrary padding to all values):
  196. var list = [123, 12345];
  197. accounting.formatColumn(list, "$ ", 0); // ["$ 123", "$ 12,345"]
  198. // List of numbers can be a multi-dimensional array (formatColumn is applied recursively):
  199. var list = [[1, 100], [900, 9]];
  200. accounting.formatColumn(list); // [["$ 1.00", "$100.00"], ["$900.00", "$ 9.00"]]</pre>
  201. <h4><strong>accounting.formatNumber()</strong></h4>
  202. <pre class="prettyprint lang-js">// Standard usage and parameters (returns string):
  203. accounting.formatNumber(number<em>, [precision = 0], [thousand = ","], [decimal = "."]</em>)
  204. // Second parameter can also be an object matching `settings.number`:
  205. accounting.formatNumber(number<em>, [object]</em>)
  206. // Example usage:
  207. accounting.formatNumber(9876543); // 9,876,543
  208. accounting.formatNumber(4999.99, 2, ".", ","); // 4.999,99
  209. // Example usage with options object:
  210. accounting.formatNumber(5318008, {
  211. precision : 3,
  212. thousand : " "
  213. });
  214. // Will recursively format an array of values:
  215. accounting.formatNumber([123456, [7890, 123]]); // ["123,456", ["7,890", "123"]]</pre>
  216. <h4><strong>accounting.toFixed()</strong></h4>
  217. <pre class="prettyprint lang-js">// Standard usage and parameters (returns string):
  218. accounting.toFixed(number<em>, [precision = 0]</em>);
  219. // Example usage:
  220. accounting.toFixed(0.615, 2); // "0.62"
  221. // Compare to regular JavaScript `Number.toFixed()` method:
  222. (0.615).toFixed(2); // "0.61"</pre>
  223. <h4><strong>accounting.unformat()</strong></h4>
  224. <pre class="prettyprint lang-js">// Standard usage and parameters (returns number):
  225. accounting.unformat(string<em>, [decimal]</em>);
  226. // Example usage:
  227. accounting.unformat("GBP &pound; 12,345,678.90"); // 12345678.9
  228. // If a non-standard decimal separator was used (eg. a comma) unformat() will need it in order to work out
  229. // which part of the number is a decimal/float:
  230. accounting.unformat("&euro; 1.000.000,00", ","); // 1000000</pre>
  231. </section>
  232. <section id="roadmap">
  233. <h2>Roadmap</h2>
  234. <h4>Next Version:</h4>
  235. <ul>
  236. <li><s>Add more fine-grained control of formatting, with negatives and zero-values</s></li>
  237. <li><s>Implement <code>map()</code> and type-checking helper methods to clean up API methods</s></li>
  238. <li>Find performance bottlenecks and work on speed optimisations</li>
  239. <li>Write more tests, docs and examples, add FAQ</li>
  240. <li>Implement <a href="https://github.com/openexchangerates/accounting.js/issues/" title="accounting.js issues">feedback</a></li>
  241. </ul>
  242. <h4>Later:</h4>
  243. <ul>
  244. <li>Add padding parameter to override amount of space between currency symbol and value.</li>
  245. <li>Add digit-grouping control, to allow eg. "$10,0000"</li>
  246. <li>Add choice of rounding method for precision (up, down or nearest-neighbour).</li>
  247. <li>Add several other general and excel-style money formatting methods.</li>
  248. <li>Create NPM package, if there's demand for it.</li>
  249. <li>Create wrapper for jQuery as a separate plugin (not in core) to allow eg. <code>$('td.accounting').formatMoney()</code></li>
  250. </ul>
  251. <p>See the <a href="https://github.com/openexchangerates/accounting.js/issues" title="accounting.js issues">Github Issues page</a> for currently active issues.</p>
  252. </section>
  253. <section id="support">
  254. <h2>Feedback / Support</h2>
  255. <p>Please create issues on the <a href="https://github.com/openexchangerates/accounting.js" title="accounting.js Github repository">accounting.js Github repository</a> if you have feedback or need support, or <a href="mailto:info@openexchangerates.org" title="Contact Open Exchange Rates">contact Open Exchange Rates here</a>.</p>
  256. </section>
  257. <section id="download">
  258. <h2>Download</h2>
  259. <ul>
  260. <li><strong><a href="https://raw.github.com/openexchangerates/accounting.js/master/accounting.js" title="accounting.js">accounting.js</a></strong> - Latest version from Github (12kb)</li>
  261. <li><strong><a href="https://raw.github.com/openexchangerates/accounting.js/master/accounting.min.js" title="accounting.min.js">accounting.min.js</a></strong> - Latest version from Github (3kb, minified)</li>
  262. <li>Or check out the <a href="https://github.com/openexchangerates/accounting.js" title="accounting.js Github repository">accounting.js Github repository</a> for the full package.</li>
  263. </ul>
  264. </section>
  265. <section id="links">
  266. <h2>Links</h2>
  267. <p>accounting.js is maintained by <strong><a href="https://openexchangerates.org" title="Open Exchange Rates free currency data API" target="_blank">Open Exchange Rates</a></strong> - the lightweight currency data API for startups, SMEs and Fortune 500s.</p>
  268. <p>Feedback, support or questions? <strong><a href="mailto:info@openexchangerates.org" title="Contact Open Exchange Rates">Contact Open Exchange Rates</a></strong> for guidance.</p>
  269. <p>Bugs, issues, suggestions or contributions? Please <strong><a href="https://github.com/openexchangerates/accounting.js" title="accounting.js Github repository">post them here</a></strong>.</p>
  270. <p>accounting.js works great with <strong><a href="http://openexchangerates.github.com/money.js" title="money.js - JavaScript currency conversion library">money.js</a></strong> - the tiny (1kb) standalone JavaScript currency conversion library, for web & nodeJS</p>
  271. <br />
  272. <hr />
  273. <p><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="josscrowcroft" data-url="http://openexchangerates.github.io/accounting.js" data-text="accounting.js - JavaScript library for money/currency formatting">Tweet</a> &nbsp; <g:plusone size="medium"></g:plusone></p>
  274. </section>
  275. <script src="accounting.min.js"></script>
  276. <script src="demo-resources/js/libs/jquery.min.js"></script>
  277. <script src="demo-resources/js/prettify.js"></script>
  278. <script type="text/javascript">
  279. // demo functions:
  280. jQuery(document).ready(function($) {
  281. var numbers = [123.5, 3456.615, 777888.99, -5432, -1234567, 0];
  282. // Use accounting.js to format the list of numbers several ways:
  283. var formatted = accounting.formatColumn(numbers, "$ "),
  284. different = accounting.formatColumn(numbers, {
  285. symbol:"HK$",
  286. precision:0,
  287. format: {
  288. pos : "%s %v",
  289. neg : "%s (%v)",
  290. zero : "%s --"
  291. }
  292. }),
  293. european = accounting.formatColumn(numbers, {
  294. symbol: '&euro; ',
  295. thousand:'.',
  296. decimal:','
  297. }),
  298. symbolAfter = accounting.formatColumn(numbers, {
  299. symbol : "GBP",
  300. format : "%v %s"
  301. });
  302. // Concat some nasty demo HTML:
  303. for ( var i = 0; i < numbers.length; i++ ) {
  304. $('<tr><td>'+numbers[i]+'</td><td>'+formatted[i]+'</td><td>'+different[i]+'</td><td>'+european[i]+'</td><td>'+symbolAfter[i]+'</td></tr>').appendTo('table#demo-table tbody');
  305. }
  306. // Try it yourself clicky demo:
  307. var $demoValue = $('#demo-number-value'),
  308. $demoSymbol = $('#demo-number-symbol'),
  309. $demoResult = $('#demo-number-result');
  310. $demoValue.add($demoSymbol).bind('keydown keyup keypress focus blur paste change', function() {
  311. var symbol = $demoSymbol.find(':selected').val(),
  312. result = accounting.formatMoney(
  313. $demoValue.val(),
  314. symbol,
  315. 2,
  316. ($demoSymbol.find(':selected').data('locale') === 'european') ? "." : ",",
  317. ($demoSymbol.find(':selected').data('locale') === 'european') ? "," : "."
  318. );
  319. $demoResult.text(result);
  320. });
  321. // Try it yourself clicky column formatting demo:
  322. var $columnValues = $('#demo-column').find('input'),
  323. $columnOutputs = $('#demo-column').find('.output'),
  324. $columnOutputs2 = $('#demo-column').find('.output2');
  325. $columnValues.bind('keydown keyup keypress focus blur paste', function() {
  326. var list = $.map( $columnValues, function(each) { return $(each).val(); } ),
  327. formatted = accounting.formatColumn(list, {
  328. format : "%s %v"
  329. }),
  330. formatted2 = accounting.formatColumn(list, {
  331. symbol : "GBP",
  332. precision : 0,
  333. format : {
  334. pos : "%s %v",
  335. neg : "%s (%v)",
  336. zero: "%s --"
  337. }
  338. });
  339. $.each($columnOutputs, function(i, each) {
  340. $(each).text(formatted[i]);
  341. });
  342. $.each($columnOutputs2, function(i, each) {
  343. $(each).text(formatted2[i]);
  344. });
  345. });
  346. });
  347. // prettify:
  348. prettyPrint();
  349. // twitter:
  350. (function(d, t) {
  351. var g = d.createElement(t),
  352. s = d.getElementsByTagName(t)[0];
  353. g.async = true;
  354. g.src = 'http://platform.twitter.com/widgets.js';
  355. s.parentNode.insertBefore(g, s);
  356. })(document, 'script');
  357. // google plus:
  358. window.___gcfg = {lang: 'en-GB'};
  359. (function() {
  360. var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
  361. po.src = 'https://apis.google.com/js/plusone.js';
  362. var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  363. })();
  364. </script>
  365. </body>
  366. </html>