Easy Number Formatting with Accounting.js
Discover the power of jQuery Accounting.js for effortlessly formatting numbers, currencies, and dates on your website, giving it a professional and polished appearance.
Numbers are everywhere on the web, from tallying unread messages to displaying likes and comments. But when it comes to presenting numbers in the context of finance or banking, some extra effort may be needed.
When you want to display numbers in a currency format, with commas or decimal points, Accounting.js is your go-to solution. It’s a JavaScript library specifically designed for handling money and currency formatting.
In this article, I’ll introduce you to the basic features of Accounting.js, and then we’ll dive into an actual example to see it in action. Let’s jump right in!
Contents
Getting Started with Accounting.js
Hey there! I’ve got something super cool to share with you. It’s called Accounting.js, and it’s a JavaScript library that can do some amazing things. The best part? You don’t even need jQuery for it – it can work all on its own! Isn’t that awesome?
If you want to get started with Accounting.js, you can download the source code from the Github repository. Just make sure to put it in the right directory, and then link the file in your HTML document. It’s as simple as that!
Let’s Talk Formatting
When it comes to numbers, Accounting.js has got your back. It offers a bunch of handy methods for formatting them. Let’s start with the basics – formatMoney(). This awesome method allows you to turn numbers into currency. Cool, right?
To use formatMoney(), all you have to do is initialize it with “accounting”, followed by the method’s name. Here’s an example:
accounting.formatMoney(2000000);
By default, Accounting.js will display the number with a dollar symbol, separate every three digits with a comma, and use a decimal point to separate dollars from cents. Pretty neat, huh?
$2,000,000.00
When it comes to numbers, different countries have different ways of separating thousands and decimals. That’s where Accounting.js comes in. It’s a tool that can be fully customized to match your local currency display preferences.
Let’s take German as an example. In German, we use dots to separate thousands and commas to separate decimals. With Accounting.js, you can format numbers accordingly:
accounting.formatMoney(2000000, { symbol: “€”, thousand: “.”, decimal: “,” });
And this is the result:
€2.000.000,00
If you want to format the number without the currency symbol, you can simply use the formatNumber() method.
Rounding Numbers
Currencies can have decimal numbers, but we often round them to make them easier to remember or guess. In Accounting.js, we can use .toFixed() to do this. Here’s an example that shows how we can remove decimal digits and round to the nearest tenth:
accounting.toFixed(102.58, 0);
Now let’s move on to building a simple currency converter using the functions mentioned earlier. We won’t be creating a complex converter, just a basic one to demonstrate what Accounting.js is capable of.
In this exercise, we’ll convert USD to two currencies: KRW (Korean Won) and JPY (Japanese Yen).
Let’s start by organizing the document structure as shown below:
From
US Dollar
$
To
Korean Won
Japanese Yen
₩ 0
So here’s what we’ve got: two rows of div. The first one is all about the starting currency, which is set to US Dollars. It’s locked down and unchangeable so you can’t pick any other option. We’ve got a cool little symbol of a dollar sign to remind us of the currency we’re converting.
In the second row, things get interesting. We have a fancy dropdown menu with two choices: Korean Won and Japanese Yen. For each of these options, we have some behind-the-scenes values stored away. There’s a value attribute that helps the computer understand what you’re selecting, and a data-symbol attribute to hold onto the currency symbol. And then there’s this neat-looking span element that will magically display the converted result for you!
Exchange Rate
As of now, one USD is equal to KRW1077.80 and JPY102.24. We can get these exchange rate values in real time from Open Exchange Rate, but for now, I’ll just put the values into a variable and round them up using the .toFixed() method:
var jpy = accounting.toFixed(102.24, 0),
krw = accounting.toFixed(1077.80, 0);
Get the Option
Now, I’m going to create a new function that will retrieve the value and data-symbol attribute from the selected dropdown option. I’ll store the values 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
I want the conversion to happen in real time. That means it will happen as you type or switch between currencies.
To make this work, I’ll assign the JavaScript events change, keyup, and keydown to #output-currency and #input-number like this:
“`
$(‘#output-currency, #input-number’).on(‘change keyup keydown’, function() {
// the stuff
});
“`
Next, I’ll use the getCurrency function we created above to retrieve the value from the dropdown option, #output-currency. The values will be stored in two separate variables called $symbol and $val, like this:
“`
var $currency = getCurrency($(‘#output-currency’)),
$symbol = $currency[‘symbol’],
$val = $currency[‘value’];
“`
Alright, here’s what we need to do. First, we have to grab the number from the input field. We also need to know the current exchange rate, which we’ve stored in the variables ‘jpy’ and ‘krw’. Using a conditional function, we’ll figure out which currency rate to use – ‘krw’ or ‘jpy’.
// Get the number
var multiplyNum = ($val == ‘jpy’) ? jpy : krw;
var $getInput = $(‘#input-number’).val();
Now that we have the necessary numbers, we can get to work on calculating the result.
var $getTotal = ($getInput * multiplyNum);
But before we show the final number, let’s make sure it’s formatted nicely using the .formatMoney() method.
var number = accounting.formatMoney($getTotal, {
symbol: $symbol,
precision: 0,
thousand: ‘,’
});
And finally, we can display the formatted number.
$(‘#output-number’).text(number);
And that’s it! You can see the demo below to see it all in action.
If you’d like, you can also try it out for yourself on our demo page.
A Final Consideration
Transforming regular numbers into currency format may seem daunting, but it’s actually quite simple. With the help of Accounting.js, this task becomes a breeze. In fact, I’ll show you just how straightforward it is to implement the necessary functions and create a basic currency converter. Are you ready to give it a shot? Let’s dive in.
Changing plain numbers into currency format doesn’t have to be difficult. Thanks to Accounting.js, it’s now a piece of cake. I’ll demonstrate how easy it is to employ the necessary functions and construct a currency converter that actually works. Why not give it a try? It’s your move.