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 function available on any instance of the Number object. However, there is a distinction between the way Number object instances and number literal instances behave.
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 the 'format' string; 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 ('string' != typeof(format)) {return '';} // sanity check
var hasComma = -1 != format.indexOf(','),
psplit = format.replace(/[^-\d\.]/g, '').split('.'),
that = this,
formatted_num = that + '',
part_whole, part_decimal, temp;
// 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);
}
// format has comma, then compute commas
if (hasComma) {
// remove precision for computation
psplit = formatted_num.split('.');
part_whole = psplit[0];
part_decimal = psplit[1] || '';
do {
temp = part_whole;
part_whole = part_whole.replace(/^(-?\d+)(\d{3})+/g, '$1,$2');
}
while (temp != part_whole);
// add the precision back in
formatted_num = part_whole + (part_decimal ? '.' + part_decimal : part_decimal);
}
// replace the number portion of the format with formatted_num
return formatted_num
};
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 calling new Number(77) or simply setting a primitive to a variable, i = 77. Only standalone number primitives like 77 do not have the prototype function.
It has been brought to my attention that this function doesn't properly handle negatives. I have cleaned the function up a bit, removing references to non-native functions, and making it work correctly on negatives. However, For a better, more robust formatting function, see http://developer.yahoo.com/yui/docs/YAHOO.util.Number.html.
