locale/ currency / number format function in Javascript

[UPDATE: This code is over 2 years 0ld now. There is a lot of room for improvement in here and some potential bugs in the code. If anyone wants an up to date version leave a comment and I’ll get to it!]

I thought I’d share this JavaScript function I wrote. It formats a number by inserting a delimiter (if specified) and rounds to ‘n’ decimal places aswell as adding a currency symbol if specified.
Be warned there are probably less verbose and more efficient functions out there. I just couldn’t find any easily from behind the firewall here!

–>

The following function will format a number to n, decimal places and apply a delimeter for easy reading and add a currency symbol, again if specified.

localeNumberFormat(amount [, currencySymbol][, delimiter][, decimalPlaces])
amount = value to format
currencySymbol = the currency Symbol to apply directly infron of the result
                 (defaults to an empty string)
delimiter = the character (or string) to use to delimit the returned value
            (defaults to a ',' [comma])
decimalPlaces = the number of decimal places the return value will be formatted (and rounded) to
                (defaults to 2)
example:
localeNumberFormat('10000.234, '$', ',', 2) returns $10,000.23

function localeNumberFormat(amount, currencySymbol, delimiter, decimalPlaces) {
	// setup some default values
	if (decimalPlaces == null || decimalPlaces == undefined) { decimalPlaces = 0; }

	//check that the value can be recognised as an Floating point number
	try {
		amount = parseFloat(amount);
		amount = amount.toFixed(decimalPlaces);
	}
	catch (e) {
		throw ('localeNumberFormat caused INVALID FLOAT with value ' + amount)
		return null;
	}

	if (delimiter == null || delimiter == undefined) { delimiter = ','; }

	// convert to string
	if (amount.match != 'function') { amount = amount.toString(); }

	// validate as numeric
	var regIsNumeric = /[^\d,\.-]+/igm;
	var results = amount.match(regIsNumeric);

	if (results != null) {
		outputText('INVALID NUMBER', eOutput)
		return null;
	}

	// setup some variables for delimiting the strings with commas
	var minus = amount.indexOf('-') >= 0 ? '-' : '';
	amount = amount.replace('-', '');
	//alert(amount);

	var amtLen = amount.length;
	var decPoint = amount.indexOf('.');
	var wholeNumberEnd = decPoint > 0 ? amtLen - (amtLen - decPoint) : amtLen;

	var wholeNumber = amount.substr(0, wholeNumberEnd);
	var fraction = amount.substr(wholeNumberEnd, amtLen - wholeNumberEnd);

	var segments = (wholeNumberEnd - (wholeNumberEnd % 3)) / 3;
	var rvsNumber = wholeNumber.split('').reverse().join('');
	var output = '';

	for (i = 0; i < wholeNumberEnd; i++) {
		if (i % 3 == 0 && i != 0 && i != wholeNumberEnd) { output += ','; }
		output += rvsNumber.charAt(i);
	}

	output = minus + currencySymbol + output.split('').reverse().join('') + fraction;

	return output;
}
Advertisements

4 thoughts on “locale/ currency / number format function in Javascript

  1. where does the delimter come into this, I tried and had a delimeter as a space ‘ ‘ and it returned the comma.

    Also how about sending in a decimal delimiter?

    1. Hey Jason,

      I wrote this code some time ago and some of it is a little flaky, sorry.

      I think the reason that space didn’t work as a delimiter was probably because my if statement is recognising it as null – try replacing the line:

      if (delimiter == null || delimiter == undefined) { delimiter = ‘,’; }

      with something like :

      delimiter = delimiter === null ? ‘,’ : delimiter;

      that should do the trick!

  2. Hi,

    You have a small error in your method, where you should be using ‘delimiter’, you’re using the hard coded ‘,’ delimiter. Correct code should be like:


    for (i = 0; i < wholeNumberEnd; i++)
    {
    if (i % 3 == 0 && i != 0 && i != wholeNumberEnd)
    {
    output += delimiter; // correction here
    }
    output += rvsNumber.charAt(i);
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s