Javascript Format Number – Easy and Flexible

Hi.. this time we’ll discuss javascript format number ( format number using javascript ).

Commonly, to format number outputted from a database, we use a serverside program, such as PHP. It is not effective at all to use client-side programs such as javascript, because we must wait until all the document elements loaded.

Then, for what is purpose formatting number using javascript?

Generally, format number using javascript used to manage input from a user in a form, either directly or indirectly. Directly means when a user directly input the value, while indirect mean when calculating other inputs value, for example making the total of all the input value in real-time.

Here is a sample of what we will do in this tutorial

I. Format Number Using Javascript – The Easy Way

On the internet, there are many scripts to format number using javascript. This time, we’ll use a bit different way by using a simple RegEx, simple and easy to learn.

The finished script looks like the following:

var number = 23456789,
	thousand_separator = ',';
	
var	number_string = number.toString(),
	rest 	  = number_string.length % 3,
	result 	  = number_string.substr(0, rest),
	thousands = number_string.substr(rest).match(/\d{3}/gi);
		
if (thousands) {
	separator = rest ? thousand_separator : '';
	result += separator + thousands.join(thousand_separator);
}

// Print the result
document.write(result); // Output: 23,456,789

Explanation:

  • Firstly, because we will break down the numbers using a javascript string function, then need to change the type data form number into string using toString() function: number.toString()
  • Next, we check whether the number is not a multiple of 3 (number_string.length % 3), the results will be stored in the result variable.

    This variable has value if the number of digits is multiple of 3, and would be empty if the number of digits multiplier 3. In this example, the thousand variable has a value of  23.

  • Furthermore, with a simple regex, we grouped the rest  by three digits, the rest is  array and stored into the thousand variable. In this example, the variable will contain [ "444"] [ "555"]
  • If the thousand variable has a value: If the number of digits is not a multiple of 3 (the rest variable has a value), the separator will be a period (.), if not, then the separator is empty. This is to avoid a leading period if the number of digits is multiple of 3, such as: .124.000
  • Lastly, we join the result variable using the operator +=

For more details, see the following image:

Javascript Format Number - The Easy Way

DEMO: For the demo, click here.

The Shorter way

Actually, there is a shorter way:

var 	number = 23456789,
	thousand_separator = ',';

var	reverse   = number.toString().split('').reverse().join(''),
	thousands = reverse.match(/\d{1,3}/g);
	result 	  = thousands.join(thousand_separator).split('').reverse().join('');

// Print result	
document.write(result); // Output: 23.456.789

Explanation:

  • First, we convert the numbers into a string (number.toString()), then, we reverse the order of these numbers (split('').reverse().Join('')), the result is 98765432, we store it in the reverse variable.
  • Furthermore, with the regex, we split this number into array, each part of array has 3 numbers + the rest: ["987"]["654"]["32"]

    Regex \d{1,3}: we take digits (\d can be changed with [0-9]) with the length of 1-3, taken from the most (3), meaning that if it can find three characters, then take 3 characters, if not two, if not one.

  • Next, we join the array using thousand separator (thousands.join('thousand_separator')). The Results is 987.654.32.
  • Last, we reverse the result (split(''),reverse().Join('')), the final result is: 23,456,789

For more detail, see the following figure:

Javascript Format Number - The Shorter Way

DEMO: The demo can be seen here.

Because the second way uses array functions a lot: split(), reverse(), and join(), then the script execution time is 3x slower than the first way, so in the rest of tutorial, we’ll use the first way. However, you are free to choose both.

II. Javascript Format Number – Supports Decimal

In a currency format, we know the term of decimal or cents, though rarely used, on a detailed system, this format is still frequently used.

For that purpose, let’s slightly change our script:

var 	number = "23456789.32",
	thousand_separator = ',',
	decimal_separator = '.';
	
var	number_string = number.toString(),
	split	  = number_string.split(decimal_separator),
	rest 	  = split[0].length % 3,
	result 	  = split[0].substr(0, rest),
	thousands = split[0].substr(rest).match(/\d{3}/g);
		
if (thousands) {
	separator = rest ? thousand_separator : '';
	result += separator + thousands.join(separator);
}
result = split[1] != undefined ? result + decimal_separator + split[1] : result;

// Print the result	
document.write(result); // Output: 23,456,789.32
The above script still compatible both for number only and number with decimal digits. The only difference from the previous script is in line 6 and 15.

Explanation:

  • On line 6, using the split method, we split the numbers into two parts using decimal_separator, first is for thousand and second is for decimal, then we save the result in the split variable.
  • Furthermore, we use split[0] for the thousands, and split[1] for the decimal.
  • On line 15, we test whether the number contains decimal (split [1]! = Undefined) if so, then we combine the decimal with the thousands using decimal separator.

DEMOSee the demo here.

III. Applying Javascript Format Number On a Form

Format number using javascript is often used in the input form associated with nominal values eg: price, quantity, discount, total price, etc…

Well, the script used to do the task is similar to the script that we have discussed previously, the only difference is we use the keyup and keydown event to capture the user keyboard keys.

Keyup event occurs when the user release the keyboard keys (after he press it), while the keydown event happens when the user press a key on the keyboard.

1. Keyup event

To capture the keyup event, we use addEventListener method. This method has been supported by all modern browsers, but for IE, it only supports it on version 9+.

The script is:

function format_number(number, prefix, thousand_separator, decimal_separator)
{
	var 	thousand_separator = thousand_separator || ',',
		decimal_separator = decimal_separator || '.',
		regex		= new RegExp('[^' + decimal_separator + '\\d]', 'g'),
		number_string = number.replace(regex, '').toString(),
		split	  = number_string.split(decimal_separator),
		rest 	  = split[0].length % 3,
		result 	  = split[0].substr(0, rest),
		thousands = split[0].substr(rest).match(/\d{3}/g);
	
	if (thousands) {
		separator = rest ? thousand_separator : '';
		result += separator + thousands.join(thousand_separator);
	}
	result = split[1] != undefined ? result + decimal_separator + split[1] : result;
	return prefix == undefined ? result : (result ? prefix + result : '');
};

The above script similar to the previous, the diferences is we wrap it into a function and add some codes:

  • We create new regex regex = new RegExp('[^' + decimal_separator + '\\d]', 'g') to remove all characters other than decimal separator and numbers. Thus, when the user presses a letter other than a comma (decimal separator) and digits, it will immediately removed.
  • We add code prefix == undefined ? result : (result ? '$ ' + result : ''); to optionally add a prefix (in this example $).

The usage example:

var input = document.getElementById('input-withprefix');
input.addEventListener('keyup', function(e)
{
	input.value = format_number(this.value, '$ ');
});

DEMO: The demo can be seen here.

2. Adding a Keydown Event

On the keyup event, when a user presses a letter key on a keyboard, then the character will appear, and will not be removed until the user releases the key.

Well, the keydown event can limit this behavior, the keyboard key is really not functioning, means that when the user presses a key, then there is no anything happened.

The limitation of this method is: We have to determine which keys we want to disabled, for that, we have to know the each keycode of the keys. The list of keyboards keycode can be seen here.

Still use the format_number function in the keyup event, we add the following script:

function limit_character(event)
{
	key = event.which || event.keyCode;
	if ( key != 188 // Comma
		 && key != 8 // Backspace
		 && key != 17 && key != 86 & key != 67 // Ctrl c, ctrl v
		 && (key < 48 || key > 57) // Non digit
		 // And many more, such as: del, left arrow dan right arrow, tab, etc...
		) 
	{
		event.preventDefault();
		return false;
	}
}

The usage example:

var input = document.getElementById('input-withprefix');
input.addEventListener('keyup', function(e)
{
	input.value = format_number(this.value, '$ ');
});

input.addEventListener('keydown', function(event)
{
	limit_character(event);
});

DEMO : For the demo, click here.

The first technique (keyup) is the most commonly used to limit the input characters on the form, because there is :something happened” when the user presses the keyboard keys, thus the user knows that there is a limitation of input characters.

If we use keydown to limit the characters, there was no reaction when the keyboard keys is pressed, the user may be ask: is there something wrong with this keyboard?

IV. Conclusion

Format number using javascript can be done in many ways, some of which we have discussed above.

Which one should we use?

Based on our discussion above, the most common use is to use the keyup event (section III.1), but to enhance the functionality, we can add an event keydown (section III.2)

That all, you have learned javascript format number.

Leave a comment