Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
javascript function that helps convert javascript number into a nice format with the function niceFormat for thousand separator, negative uses () etc
if (!Number.prototype.niceFormat) {
Number.prototype.niceFormat = function(options) {
var defaultOptions = {
thousandSeparator: ',',
leftPad: 0,
decimalPlaces: 2,
negative: '()'
};
var env = defaultOptions;
if (typeof options != 'undefined') {
for (option in env) {
if (options.hasOwnProperty(option)
&& typeof options[option] != 'undefined') {
env[option] = options[option];
}
}
}
if (env.thousandSeparator == false) {
env.thousandSeparator = '';
}
var number = this.toFixed(env.decimalPlaces + 1).toString();
var simpleNumber = '';
// Strips out the dollar sign and commas.
for (var i = 0; i < number.length; ++i)
{
if ("0123456789.".indexOf(number.charAt(i)) >= 0)
simpleNumber += number.charAt(i);
}
number = parseFloat(simpleNumber);
if (isNaN(number)) {
number = 0;
}
if (env.leftPad == 0) {
env.leftPad = 1;
}
var integerPart = (env.decimalPlaces > 0 ? Math.floor(number) : Math.round(number));
var string = "";
for (var i = 0; i < env.leftPad || integerPart > 0; ++i)
{
// Insert a comma every three digits.
if (env.thousandSeparator.length > 0 && string.match(/^\d\d\d/))
string = env.thousandSeparator + string;
string = (integerPart % 10) + string;
integerPart = Math.floor(integerPart / 10);
}
if (env.decimalPlaces > 0)
{
number -= Math.floor(number);
number *= Math.pow(10, env.decimalPlaces);
string += "." + number.niceFormat({leftPad: env.decimalPlaces, decimalPlaces: 0, thousandSeparator:false});
}
if (this < 0) {
if (env.negative == '()') {
string = '(' + string + ')';
} else {
string = env.negative + string;
}
}
return string;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment