Skip to content

Instantly share code, notes, and snippets.

@supasympa
Created July 11, 2011 10:15
Show Gist options
  • Save supasympa/1075645 to your computer and use it in GitHub Desktop.
Save supasympa/1075645 to your computer and use it in GitHub Desktop.
Javascript Locale Currency format
function localeNumberFormat(amount, currencySymbol, delimiter, decimalPlaces) {
// setup some default values
if (typeof decimalPlaces === 'undefined' || decimalPlaces === null) {
decimalPlaces = 0;
}
if (typeof decimalPlaces === 'undefined' || delimiter === null) { delimiter = ','; }
//check that the value can be recognised as an Floating point number
try {
amount = parseFloat(amount);
amount = amount.toFixed(decimalPlaces);
}
catch (e) {
return 'NaN';
}
// setup some variables for delimiting the strings with commas
var isNegative = amount.indexOf('-') >= 0 ? '-' : '';
amount = amount.replace('-', '');
var amtLen = amount.length;
var decPoint = amount.indexOf('.');
var wholeNumberEnd = decPoint > 0 ? amtLen - (amtLen - decPoint) : amtLen;
var wholeNumber = amount.substr(0, wholeNumberEnd);
var decimal = amount.substr(wholeNumberEnd, amtLen - wholeNumberEnd);
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 = isNegative + currencySymbol + output.split('').reverse().join('') + decimal;
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment