Formatting Numbers with Accounting.js

By . Filed in Web Design

While on the Web we use numbers to show unread messages, comments, likes, tweets, and bunch of other item counts, when it comes to formatting numbers for use in a bank or a financial institution, displaying a number may require some workarounds.

If you need numbers to appear in currency format or split with commas or decimal points, then you will love using Accounting.js, a JavaScript library for Money and Currency formatting.

In this article, we are going to show you some of its basic functionalities, then we will utilize it in an actual example to showcase how it works. Let’s get started.

Getting Started

Accounting.js is a JavaScript library with no dependencies. You don’t need jQuery to use it; it can run on its own. Download the source code from the Github repository, put it in an appropriate directory, and link the file in the HTML document.

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

Basic Formatting

Accounting.js offers a few methods for formatting numbers. And the first one that we are going to take a look at is formatMoney(). This method is the basic function to turn numbers into currency. To use it, each method is intialized by accounting and then followed by the method’s name. For example:

accounting.formatMoney(2000000);

In the default settings, Accounting.js will display the above example with the dollar symbol, separate each three digit with a comma, and use a decimal point to separate dollars from cents.

$2,000,000.00

Some countries use different separators for every three digits (thousands) and decimal. Accounting.js is fully localisable. If the default output is not the way your local currency displayed, you can make changes with Options.

Below, we take German as an the example, which uses dot separators for thousand and comma for decimal:

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

This will output:

€2.000.000,00

If you would like to format the number without the currency symbol, you can use formatNumber() method.

Rounding Number

Currencies may have decimals. But we usually round them up or down to the nearest value to make the number simpler to remember or guess. In Accounting.js, we can use .toFixed() to do so. This example shows how we remove the decimal digits as well as round them to the nearest tenth:

accounting.toFixed(102.58, 0);

The output is:

103

Building a Simple Currency Converter

In this section, we will be using those functions mentioned above to build a currency converter. We won’t be building an extensive converter, just a simple one to illustrate what Accounting.js can do.

In the exercise, we will convert USD to 2 currencies namely KRW (Korean Won) and JPY (Japanese Yen).

Let’s layout the 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>

As we can see above, we have two rows of div. The first row contains a dropdown option which is set to USD, and disabled so the user won’t be able to select the other option. This row also contains an number type input field where we will enter the amount of USD to convert.

In the second row, we have a dropdown option too, containing two currency options: Korean Won and Japanese Yen. Each option has a value attribute, and a data-symbol attribute to store the currency symbol. We use a span element to output the converted result.

Exchange Rate

At the time of this writing 1 USD is equal to KRW1077.80 and JPY102.24. We can retrieve these exchange rate values in real time from Open Exchange Rate. But, for now, we simply put the value in a variable with .toFixed() method to round up the number:

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

Get the Option

Next, we will create a new function to get the value from the value and data-symbol attribute from the dropdown option. The values then are 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 want the conversion to occur in real time. It means that it will happen as the user is typing within the input field or switching between currencies.

To achieve this idea, we will assign #output-currency as well as #input-number with three JavaScript Events namely change, keyup, and keydown this way:

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

Then, we will retrieve the value from the dropdown option, #output-currency, by using the getCurrency function that we created above. The values are separated within two different variables namely $symbol and $val, as follows.

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

We also need to get the number from the input field, and the current exchange rate value that we have set in jpy and krw variable; using the conditional function we can decide which currency rate (krw or jpy) to use.

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

With those number above, we can calculate the result.

var	$getTotal   = ($getInput * mulitplyNum);

But, before we output the number, let’s wrap it in a proper format using .formatMoney() method:

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

And lastly, we output the final formatted number.

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

And we’re done. You can see the demo in action below.

You can also try it yourself from our demo page.

Final Thought

Formatting plain number into currency is not as hard as you might have thought. Using Accounting.js, this thing becomes very easy. And we have also shown you how to implement the functions to build a simple working currency converter. Give it a go.

Author:

Thoriq is a writer for hongkiat.com. He is also a web developer with very unpredictable sleep cycle.

Advertisement

Comments are closed. Contact Us.