All numbers in JavaScript are 64bit (8 bytes) floating point numbers which yields an effective range of 5e-324 (negative) to 1.7976931348623157e+308 (positive). Because JavaScript is loosely typed and the plus operator also concatenates, you can easily convert JavaScript Numbers to Strings using: 1 + "". JavaScript also has some built in number logic attached to the Number Object. However, most people never realize this, as they do not understand the difference between a JavaScript Number literal and a Number object.
Example 1: Literal vs. Object
var numericLiteral = 0; var numericObject = new Number(0); if (numericLiteral) { } // false because 0 is a falsy, will not be executed. if (numericObject) { } // true because numericObject exists as an object, will be executed.
The important distinction, as seen in the example above, is that Number objects are not falsy when they are ZERO. Since, they are Objects, they are truthy when they have any value except undefined and null. By default all Number variables (both numbericLiteral and numbericObject) have several functions available on their prototype:
Example 2: Number Functions
method IE FireFox Explaination toExponential 5.5 1.5 Returns the expotential value of the number. toFixed 5.5 1.5 Returns a number with a specified number of decimals. toLocaleString 3 2.0 Displays the number using regional preferences. toPrecision 5.5 1.5 Returns a string with a specified number of digits. toSource --- 1.5 Returns the source code used to make the number. toString 3 2.0 Returns the number as a string. ValueOf 3 2.0 See toString
* Table From The Complete JavaScript Number Reference
The toFixed
and toPrecision
method come in very handy when converting Numbers to Strings with a given number of decimals or precision. However, they do not help when you want to use commas to represent thousands, millions, etc. For this task we will need to attach another method format
to Number, which will allow us to add not only comma, but also additional non-number characters (like $
and %
).
Example 3: Format Function
/** * Formats the number according to theformatstring; adherses to the american number standard where a comma is inserted after every 3 digits. * note: there should be only 1 contiguous number in the format, where a number consists of digits, period, and commas * any other characters can be wrapped around this number, including$,%, or text * examples (123456.789): *0- (123456) show only digits, no precision *0.00- (123456.78) show only digits, 2 precision *0.0000- (123456.7890) show only digits, 4 precision *0,000- (123,456) show comma and digits, no precision *0,000.00- (123,456.78) show comma and digits, 2 precision *0,0.00- (123,456.78) shortcut method, show comma and digits, 2 precision * * @method format * @param format {string} the way you would like to format this text * @return {string} the formatted number * @public */ Number.prototype.format = function(format) { if (! isType(format,string)) {return ;} // sanity check var hasComma = -1 < format.indexOf(,), psplit = format.stripNonNumeric().split(.), that = this; // compute precision if (1 < psplit.length) { // fix number precision that = that.toFixed(psplit[1].length); } // error: too many periods else if (2 < psplit.length) { throw(NumberFormatException: invalid format, formats should have no more than 1 period:+ format); } // remove precision else { that = that.toFixed(0); } // get the string now that precision is correct var fnum = that.toString(); // format has comma, then compute commas if (hasComma) { // remove precision for computation psplit = fnum.split(.); var cnum = psplit[0], parr = [], j = cnum.length, m = Math.floor(j / 3), n = cnum.length % 3 || 3; // n cannot be ZERO or causes infinite loop // break the number into chunks of 3 digits; first chunk may be less than 3 for (var i = 0; i < j; i += n) { if (i != 0) {n = 3;} parr[parr.length] = cnum.substr(i, n); m -= 1; } // put chunks back together, separated by comma fnum = parr.join(,); // add the precision back in if (psplit[1]) {fnum +=.+ psplit[1];} } // replace the number portion of the format with fnum return format.replace(/[\d,?\.?]+/, fnum); };
See the comment block for help on how this function should behave. Basically, you can pass in a String as the format that contain any one number (in the format that you like) and the result will replace the number in the format String with the properly formatted Number object.
****** Update ******
All number variables have the Functions of "Number.prototype" available to them whether instantiated by call "new Number()" or simply setting a primitive to a variable. Only number primitives like "77" do not have the prototype function.