Skip to content

Instantly share code, notes, and snippets.

@andrewlistopadov
Created July 10, 2015 08:30
Show Gist options
  • Save andrewlistopadov/fa32594cfbdcbbec618c to your computer and use it in GitHub Desktop.
Save andrewlistopadov/fa32594cfbdcbbec618c to your computer and use it in GitHub Desktop.
JS: convert number to money string
'use strict';
/**
* isNumeric(n) returns a bool value
* is "n" number or not
*
* @param {Number} n
* @return {Bool} result
*/
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
/**
* moneyFormat(num, count, sep, tab) returns money formatting string
* @param {Number} num
* @param {Number} count
* @param {String} sep
* @param {String} tab
*
* @return {String} result
*/
function moneyFormat(num, count, sep, tab) {
if(!isNumeric(num)) {
throw Error('Argument "num" is not a number');
}
count = isNumeric(count = Math.abs(count)) ? count : 2;
sep = sep === undefined ? '.' : sep;
tab = tab === undefined ? ' ' : tab;
var sign = num < 0 ? '-' : '';
var absVal = parseInt(num = Math.abs(+num || 0).toFixed(count)) + '';
var unCount = (unCount = absVal.length) > 3 ? unCount % 3 : 0; // count of ungrouped decimal by "tab"
return sign + (unCount ? absVal.substr(0, unCount) + tab : '')
+ absVal.substr(unCount).replace(/(\d{3})(?=\d)/g, '$1' + tab)
+ (count ? sep + Math.abs(num - absVal).toFixed(count).slice(2) : '');
}
/**
* For tests
*/
var nums = [20000000000000000.12, 2000.00, .12, .123, -1234.556, '45.12',
'45,12', 'asd', null, '', undefined, -Infinity, Infinity, NaN, false, true];
var v;
for(v of nums) {
try {
console.log('moneyFormat: ' + moneyFormat(v));
} catch(e) {
console.log(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment