accounting.js: JavaScript number and currency formatting library


accounting.js is a tiny JavaScript library by Open Exchange Rates, providing simple and advanced number, money and currency formatting.

    <p>Features custom output formats, parsing/unformatting of numbers, easy localisation and spreadsheet-style column formatting (to line up symbols and decimals).</p>

    <p>It's lightweight, has no dependencies and is suitable for all client-side and server-side JavaScript applications.</p>

    <p><a href="" class="twitter-share-button" data-count="horizontal" data-via="josscrowcroft" data-url="" data-text="accounting.js - JavaScript library for money/currency formatting">Tweet</a> &nbsp; <g:plusone size="medium"></g:plusone></p>
        <li><a href="#methods" title="library methods overvew">methods &amp; examples</a>
        <li><a href="#demo" title="demo">demo</a>
        <li><a href="#instructions" title="instructions">instructions</a>
        <li><a href="#documentation" title="documentation">documentation</a>
        <li><a href="#roadmap" title="roadmap">roadmap</a>
        <li><a href="#support" title="support">feedback / support</a>
        <li><a href="#download" title="download">download</a>
        <li><a href="#links" title="links">links</a>

<section id="methods">
    <h2>Library Methods</h2>

    <h4><strong>formatMoney()</strong> - format any number into currency</h4>

    <p>The most basic library function for formatting numbers as money values, with customisable currency symbol, precision (decimal places), and thousand/decimal separators:</p>
    <pre class="prettyprint lang-js">// Default usage:

accounting.formatMoney(12345678); // $12,345,678.00

// European formatting (custom symbol and separators), can also use options object as second parameter: accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99

// Negative values can be formatted nicely: accounting.formatMoney(-500000, "£ ", 0); // £ -500,000

// Simple format string allows control of symbol position (%v = value, %s = symbol): accounting.formatMoney(5318008, { symbol: "GBP", format: "%v %s" }); // 5,318,008.00 GBP

    <h4><strong>formatColumn()</strong> - format a list of values for column-display</h4>

    <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>
    <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>

    <table id="demo-table">
                <th>Original Number:</th>
                <th>With accounting.js:</th>
                <th>Different settings:</th>
                <th>European format:</th>
                <th>Symbol after value:</th>
    <pre class="prettyprint lang-js">// Format list of numbers for display:

accounting.formatColumn([123.5, 3456.49, 777888.99, 12345678, -5432], "$ ");

    <h4><strong>formatNumber()</strong> - format a number with custom precision and localisation</h4>

    <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>
    <pre class="prettyprint lang-js">accounting.formatNumber(5318008); // 5,318,008

accounting.formatNumber(9876543.21, 3, " "); // 9 876 543.210

    <h4><strong>toFixed()</strong> - better rounding for floating point numbers</h4>

    <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>
    <pre class="prettyprint lang-js">(0.615).toFixed(2); // "0.61"

accounting.toFixed(0.615, 2); // "0.62"

    <h4><strong>unformat()</strong> - parse a value from any formatted number/currency string</h4>

    <p>Takes any number and removes all currency formatting. Aliased as <code>accounting.parse()</code></p>
    <pre class="prettyprint lang-js">accounting.unformat("&pound; 12,345,678.90 GBP"); // 12345678.9</pre>

<section id="demo">
    <h2>Demo / Try it out</h2>

    <h4>Money formatting:</h4>

    <div class="well">
        <p>Enter any number into the box and choose currency. Uses <code>accounting.formatMoney()</code>:</p>
            <select id="demo-number-symbol">
                <option value="$ ">$</option>
                <option value="&pound; ">&pound;</option>
                <option value="HK$ ">HK$</option>
                <option data-locale="european" value="&euro; ">&euro; </option>
            <input type="text" maxlength="20" class="" id="demo-number-value" value="" />
        <p>Result: <strong><span id="demo-number-result">$ 0.00</span></strong></p>

    <h4>Column formatting:</h4>

    <div class="well">
        <p>Edit the values in the table to see how <strong>formatColumn()</strong> keeps them aligned:</p>
        <table id="demo-column">
                    <td><input type="text" value="1000000" maxlength="20" /></td>
                    <td class="output">$ 1,000,000.00</td>
                    <td class="output2">GBP 1,000,000</td>
                    <td><input type="text" value="-5000" maxlength="20" /></td>
                    <td class="output">$    -5,000.00</td>
                    <td class="output2">GBP   (5,000)</td>
                    <td><input type="text" value="0" maxlength="20" /></td>
                    <td class="output">$         0.00</td>
                    <td class="output2">GBP        --</td>

<section id="instructions">
    <h2>Basic Instructions:</h2>

    <p>1. Download the script and put it somewhere, then reference it in your HTML like so:</p>
    <pre class="prettyprint">&lt;script src=&quot;path/to/accounting.js&quot;&gt;&lt;/script&gt;

<script type="text/javascript"> // Library ready to use: accounting.formatMoney(5318008); </script>

    <p>2. See the documentation and source-code for full method/parameter information.</p>

<section id="documentation">


    <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>


    <pre class="prettyprint lang-js">// Settings object that controls default parameters for library methods:

accounting.settings = { currency: { symbol : "$", // default currency symbol is '$' format: "%s%v", // controls output: %s = symbol, %v = value/number (can be object: see below) decimal : ".", // decimal point separator thousand: ",", // thousands separator precision : 2 // decimal places }, number: { precision : 0, // default precision on numbers is 0 thousand: ",", decimal : "." } }

// These can be changed externally to edit the library's defaults: accounting.settings.currency.format = "%s %v";

// Format can be an object, with pos, neg and zero: accounting.settings.currency.format = { pos : "%s %v", // for positive values, eg. "$ 1.00" (required) neg : "%s (%v)", // for negative values, eg. "$ (1.00)" [optional] zero: "%s -- " // for zero values, eg. "$ --" [optional] };

// Example using underscore.js - extend default settings (also works with $.extend in jQuery): accounting.settings.number = _.defaults({ precision: 2, thousand: " " }, accounting.settings.number);


    <pre class="prettyprint lang-js">// Standard usage and parameters (returns string):

accounting.formatMoney(number,[symbol = "$"],[precision = 2],[thousand = ","],[decimal = "."],[format = "%s%v"])

// Second parameter can be an object: accounting.formatMoney(number, [options])

// Available fields in options object, matching settings.currency: var options = { symbol : "$", decimal : ".", thousand: ",", precision : 2, format: "%s%v" };

// Example usage: accounting.formatMoney(12345678); // $12,345,678.00 accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99 accounting.formatMoney(-500000, "£ ", 0); // £ -500,000

// Example usage with options object: accounting.formatMoney(5318008, { symbol: "GBP", precision: 0, thousand: "&middot", format: { pos : "%s %v", neg : "%s (%v)", zero: "%s --" } });

// Will recursively format an array of values: accounting.formatMoney([123, 456, [78, 9]], "$", 0); // ["$123", "$456", ["$78", "$9"]]


    <pre class="prettyprint lang-js">// Standard usage and parameters (returns array):

accounting.formatColumn(list, [symbol = "$"],[precision = 2],[thousand = ","],[decimal = "."],[format = "%s%v"])

// Second parameter can be an object (see formatNumber for available options): accounting.formatColumn(list, [options])

// Example usage (NB. use a space after the symbol to add arbitrary padding to all values): var list = [123, 12345]; accounting.formatColumn(list, "$ ", 0); // ["$ 123", "$ 12,345"]

// List of numbers can be a multi-dimensional array (formatColumn is applied recursively): var list = [[1, 100], [900, 9]]; accounting.formatColumn(list); // [["$ 1.00", "$100.00"], ["$900.00", "$ 9.00"]]


    <pre class="prettyprint lang-js">// Standard usage and parameters (returns string):

accounting.formatNumber(number, [precision = 0], [thousand = ","], [decimal = "."])

// Second parameter can also be an object matching settings.number: accounting.formatNumber(number, [object])

// Example usage: accounting.formatNumber(9876543); // 9,876,543 accounting.formatNumber(4999.99, 2, ".", ","); // 4.999,99

// Example usage with options object: accounting.formatNumber(5318008, { precision : 3, thousand : " " });

// Will recursively format an array of values: accounting.formatNumber([123456, [7890, 123]]); // ["123,456", ["7,890", "123"]]


    <pre class="prettyprint lang-js">// Standard usage and parameters (returns string):

accounting.toFixed(number, [precision = 0]);

// Example usage: accounting.toFixed(0.615, 2); // "0.62"

// Compare to regular JavaScript Number.toFixed() method: (0.615).toFixed(2); // "0.61"


    <pre class="prettyprint lang-js">// Standard usage and parameters (returns number):

accounting.unformat(string, [decimal]);

// Example usage: accounting.unformat("GBP £ 12,345,678.90"); // 12345678.9

// If a non-standard decimal separator was used (eg. a comma) unformat() will need it in order to work out // which part of the number is a decimal/float: accounting.unformat("€ 1.000.000,00", ","); // 1000000


<section id="roadmap">

    <h4>Next Version:</h4>
        <li><s>Add more fine-grained control of formatting, with negatives and zero-values</s></li>
        <li><s>Implement <code>map()</code> and type-checking helper methods to clean up API methods</s></li>
        <li>Find performance bottlenecks and work on speed optimisations</li>
        <li>Write more tests, docs and examples, add FAQ</li>
        <li>Implement <a href="" title="accounting.js issues">feedback</a></li>

        <li>Add padding parameter to override amount of space between currency symbol and value.</li>
        <li>Add digit-grouping control, to allow eg. "$10,0000"</li>
        <li>Add choice of rounding method for precision (up, down or nearest-neighbour).</li>
        <li>Add several other general and excel-style money formatting methods.</li>
        <li>Create NPM package, if there's demand for it.</li>
        <li>Create wrapper for jQuery as a separate plugin (not in core) to allow eg. <code>$('td.accounting').formatMoney()</code></li>

    <p>See the <a href="" title="accounting.js issues">Github Issues page</a> for currently active issues.</p>

<section id="support">
    <h2>Feedback / Support</h2>

    <p>Please create issues on the <a href="" title="accounting.js Github repository">accounting.js Github repository</a> if you have feedback or need support, or <a href="" title="Contact Open Exchange Rates">contact Open Exchange Rates here</a>.</p>

<section id="download">

        <li><strong><a href="" title="accounting.js">accounting.js</a></strong> - Latest version from Github (12kb)</li>
        <li><strong><a href="" title="accounting.min.js">accounting.min.js</a></strong> - Latest version from Github (3kb, minified)</li>
        <li>Or check out the <a href="" title="accounting.js Github repository">accounting.js Github repository</a> for the full package.</li>

<section id="links">

    <p>accounting.js is maintained by <strong><a href="" 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>
    <p>Feedback, support or questions? <strong><a href="" title="Contact Open Exchange Rates">Contact Open Exchange Rates</a></strong> for guidance.</p>
    <p>Bugs, issues, suggestions or contributions? Please <strong><a href="" title="accounting.js Github repository">post them here</a></strong>.</p>
    <p>accounting.js works great with <strong><a href="" title="money.js - JavaScript currency conversion library">money.js</a></strong> - the tiny (1kb) standalone JavaScript currency conversion library, for web & nodeJS</p>

    <br />
    <hr />
    <p><a href="" class="twitter-share-button" data-count="horizontal" data-via="josscrowcroft" data-url="" data-text="accounting.js - JavaScript library for money/currency formatting">Tweet</a> &nbsp; <g:plusone size="medium"></g:plusone></p>