JavaScript

# Javascript Number Format Example

We’ve all had to customize the formatting of a specific number, or a ton of them.

Most of the time, if you have to format many numbers, it’s boring and annoying to format each one of them, so that’s why we use some specific ways in Javascript.

One of the most typical formatting you do to numbers is adding commas to big numbers, especially to identify thousands or millions.

The code would go like this:

```function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}

var a;
a = numberWithCommas(1234567.89);
```

In this function we’ve taken the number as an argument, turned it into a string, and split the decimal part from the most significant part of the number. Then we’ve put a comma after each three digits in the main number, starting from the least significant one. To finish up, we’ve joined the number with it’s decimal part, and there you go.

## Rounding the number to a certain number of places

When turning in lab reports in some of my engineering subject, one of the things I hated most was when I was deducted points for not presenting some numbers in a specific precision or numbers after the decimal point (even if it was a full number! ). Then, I still didn’t know I could do this:

```var num = 10;
var result = num.toFixed(2); //  equal to 10.00

num = 930.9875;
result = num.toFixed(3); // equal to 930.988

num = 500.2349;
result = num.toPrecision(4); // equal to 500.2

num = 5000.2349;
result = num.toPrecision(4); // equal to 5000

num = 555.55;
result = num.toPrecision(2); // equal to 5.6e+2
```

As you can see, the function `toFixed()` rounds up the number so that it has as many digits after the decimal point as the number we give to it as an argument, while the function `toPrecision()` expresses the number in as many digits as we have specified in the argument.

However there are some versions of IE (less than 5.5) and NS (less than 6) that do not support these two methods, in which case, after detecting whether the browser supports the method or not, if not you’d have to create a much uglier and annoying function to solve these issues, though it’s still easy.

## Currencies

The `toFixed()` method may be considered perfect for expressing number in the currency format, by some people. Of course, we the perfectionists want visible dollar signs there. I would recommend using these two libraries for that, and much more: `accounting.js` and `Numeral.js`

accounting.js

This library features custom output formats, parsing/unformatting of numbers, easy localisation and spreadsheet-style column formatting (to line up symbols and decimals). It has no dependencies and can be used for both client-side and server-side Javascript apps.

It only has 5 methods:

1. formatMoney()
2. This method can be used for formatting numbers as money values, with currency signs, commas and precision. It can be used like this:

```accounting.formatMoney(4999.99, "€", 2, ",", "."); // €4,999.99
```

Still, you can just pass the number as an argument and by default it will format it with the dollar symbol. You can control the position of the currency symbol, whether you want it to be before the number or after it by using the method this way:

```accounting.formatMoney(5318008, { symbol: "GBP",  format: "%v %s" }); // 5,318,008.00 GBP
```
3. formatColumn()
4. This method formats a list of data for table-like display.

5. formatNumber()
6. toFixed()
7. These two methods are basically the same ones we explained for rounding numbers up, with minor changes in the `formatNumbers()` one.

8. unformat()
9. This method removes the formatting of a number presented in a specific form.

Numeral.js

Using this library, numbers can be formatted to look like currency, bytes, percentages, or even plain numbers with decimal points and thousand separators (commas).

The values are always accessible even though you’re using the functions contained by this library, which can come in handy at times. Also it gives you the opportunity to set e default formatting in general, and custom zero formatting for when the value is a zero. Also you can use thousand separators and abbreviations and also currency symbols for specific languages.
It is used like this:

```var string = numeral(1000.234).format('\$0,0.00');
// '\$1,000.23'
```

We put the number and the format we want it to have, and the library’s function does all the work. This library was inspired and heavily influenced by `Moment.js`, which means it’s just as awesome, though simpler. And for those of you who want a challenge, the author wants help in improving it, so there’s your chance!

This was an example of number formatting using Javascript.

You can download the full source code of this example here: NumberFormatting

### Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Inline Feedbacks