How to Use Accounting.js for Effective Number Formatting

Learn how to use jQuery Accounting.js to format numbers, currencies, and dates in your web applications for a professional and polished look.

On the internet, we often see numbers representing unread messages, comments, likes, and tweets, among other things. But when it comes to the precise demands of a financial institution or bank, displaying numbers can be a bit more complicated.

For those who need numbers presented in a currency format or separated by commas and decimal points, the JavaScript library Accounting.js can be a fantastic tool for money and currency formatting.

In this article, we’ll explore some basic functionalities of Accounting.js and then demonstrate its practical use with a real-world example. Let’s dive in.

Getting Started with Accounting.js

Accounting.js is a standalone JavaScript library that does not require jQuery or any other dependencies. Simply download the source code from the GitHub repository, place it in a suitable directory, and link the file in your HTML document.

<script src="js/accounting.js"></script>

Basic Formatting Techniques

Accounting.js provides several methods for formatting numbers. The first method we’ll look at is formatMoney(), which is used to convert numbers into currency format. You start by calling accounting followed by the method’s name, like so:

accounting.formatMoney(2000000);

In its default configuration, Accounting.js will format the number as follows: it adds a dollar symbol, separates every three digits with a comma, and uses a decimal point to distinguish dollars from cents.

$2,000,000.00

Accounting.js can also be adjusted to match local formatting standards. For instance, if your local currency is displayed differently, you can customize the output with various Options.

As an example, here’s how you would format numbers for Germany, which uses periods as thousand separators and commas for decimals:

	accounting.formatMoney(2000000, { 
	symbol : "€",
	thousand : ".",
	decimal : ",",
});

The result will look like this:

€2.000.000,00

To format a number without including a currency symbol, you can use the formatNumber() method.

Rounding Numbers

Since currencies often include decimals, rounding them to the nearest whole number can simplify calculations. With Accounting.js, you can achieve this using the .toFixed() method. This function rounds numbers to the nearest decimal or whole number. For example:

accounting.toFixed(102.58, 0);

This will round the number to:

103

Creating a Basic Currency Converter

In this section, we will use the functions discussed earlier to create a simple currency converter. This will not be an extensive converter but rather a straightforward one to demonstrate the capabilities of Accounting.js.

For this example, we will convert USD into two currencies: KRW (Korean Won) and JPY (Japanese Yen).

Let’s outline our document structure as follows:

<div class="currency-option">
  <div class="row">
    <h4 class="heading">From</h4>
    <select id="input-currency" disabled>
      <option value="USD" data-symbol="$" selected>US Dollar</option>
    </select>
    <span id="input-symbol">$</span>
    <input id="input-number" class="input" type="number" min="0">
  </div>

  <div class="row">
    <h4 class="heading">To</h4>
    <select id="output-currency">
      <option value="krw" data-symbol="₩" selected>Korean Won</option>
      <option value="jpy" data-symbol="¥">Japanese Yen</option>
    </select>
    <span id="output-number">₩ 0</span>
  </div>
</div>

The document structure laid out above includes two rows within a div. The first row features a dropdown menu set to USD and disabled, preventing the user from changing it. This row also contains a numeric input field where users will enter the amount of USD to be converted.

The second row also includes a dropdown menu, this time with options for converting to either Korean Won or Japanese Yen. Each option is detailed with a value attribute and a data-symbol attribute to display the currency symbol. The conversion results are shown in a span element next to the dropdown.

Exchange Rate Details

As of this writing, 1 USD is equivalent to KRW 1077.80 and JPY 102.24. While these exchange rates can be fetched in real time from Open Exchange Rates, for the purposes of this example, we’ll store the values in variables using the .toFixed() method to round them to whole numbers:

var jpy = accounting.toFixed(102.24, 0),
    krw = accounting.toFixed(1077.80, 0);

Retrieving Currency Options

Next, we will develop a function to extract the currency value and symbol from the selected option in our dropdown menu. These values are then stored in an Array.

var getCurrency = function(elem) {
    var $curAbbr = elem.find(':selected').val(),
        $curSign = elem.find(':selected').data('symbol');
    return {
        'symbol' : $curSign,
        'value' : $curAbbr,
    };
};

The Conversion Function

We aim for the currency conversion to happen in real-time, which means it should occur as the user types or switches between currency options.

To implement this, we will attach three JavaScript events to #output-currency and #input-number: change, keyup, and keydown. Here’s how we do it:

$('#output-currency, #input-number').on('change keyup keydown', function() {
    // the stuff
});

We then use the getCurrency function to fetch the value from the dropdown option #output-currency. The values are stored in two variables: $symbol and $val.

var $currency = getCurrency($('#output-currency')),
    $symbol = $currency['symbol'],
    $val = $currency['value'];

We also need to capture the number from the input field, and decide which currency rate to use based on the value of $val, whether it’s jpy or krw.

var multiplyNum = ($val == 'jpy') ? jpy : krw;
var $getInput = $('#input-number').val();

With the input value and currency rate, we calculate the result.

var $getTotal = $getInput * multiplyNum;

Before displaying the result, we format the number using the .formatMoney() method:

var number = accounting.formatMoney($getTotal, {
    symbol : $symbol,
    precision : 0,
    thousand : ','
});

Finally, we display the formatted total in the specified output element.

$('#output-number').text(number);

Below is a demo of the converter in action:

Demo of simple currency converter using Accounting.js

You can also try it yourself from our demo page.

View demo Download source

Final Thoughts

Formatting numbers into currency formats is simpler than it might seem. With Accounting.js, this task becomes straightforward. We have also demonstrated how to use these functions to create a working simple currency converter. Give it a try.

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail