Created
July 1, 2014 09:17
-
-
Save simkimsia/5744ffa79eb90baa0585 to your computer and use it in GitHub Desktop.
javascript function that helps convert javascript number into a nice format with the function niceFormat for thousand separator, negative uses () etc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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