Académique Documents
Professionnel Documents
Culture Documents
Precision
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) at the time this article was written (this may eventually change to 128 bits in the future as 64 bit processors become commonplace and the ECMA standards evolve). Integers are considered reliable (numbers without a period or exponent notation) to 15 digits (9e15) . Floating point numbers are considered only as reliable as possible and no more! This is an especially important concept to understand for currency manipulation as 0.06 + 0.01 resolves to 0.06999999999999999 instead of 0.07.
[1]
3/17/2011
Since Javascript stores all numbers as base ten decimals, you'll need to use the "toString()" method of the number to convert the number into a base other than 10. Unfortunately, the "toString()" method does not create the leading zero for octal numbers or the leading 0x for hexadecimal numbers so you'll need to add those manually if you want to be able to further work with the numbers. Simply specify the base of the number you want as the first argument, 16 for hexadecimal and 8 for octal. You can even specify 2 for binary.
var num=255; document.writeln(num.toString(16)+' hex<BR>'); // Outputs: ff document.writeln(num.toString(8)+' octal<BR>'); // Outputs: 377 document.writeln(num.toString(2)+' binary<BR>'); // Outputs: 11111111
Arithmetic Operators
Operator + * / % ++ -Description Addition (Concatenation) Subtraction (Unary conversion) Multiplication Division Remainder/Modulus [pre/post]Increment [pre/post]Decrement
2/10
hunlock.com//The_Complete_Javascr
3/17/2011
Special Note on Addition (+): The plus sign indicates addition, unfortunately in Javascript it also represents concatenation so you should be extremely mindful of where and how you use this operator. Once your number has become concatenated with a string all further operations represent concatenation and not addition as you can see in the following example.
alert(2+4+8+' Addition/Concatenation '+2+4+8); //Outputs: 14 Addition/Concatenation 248
Here, Javascript does addition up to the string where the result of that addition (14) is concatenated with the string, however the second set of numbers is treated as concatenation and NOT addition resulting in an entierly different, and unexpected result. You can correct this by enclosing the second set of numbers in parenthesis.
alert(2+4+8+' Addition/Concatenation '+(2+4+8)); //Outputs: 14 Addition/Concatenation 14
The plus sign can also be used to indicate a positive number when defining a constant. For this purpose the + sign is effectively ignored. The + sign will not convert a negative number to a positive number in the same manner as a minus sign.
var x = +-1000; document.writeln(+x+'<BR>'); // Outputs: -1000 var x = +1000; document.writeln(+x+'<BR>'); // Outputs: 1000 document.writeln(x+'<BR>'); // Outputs: 1000
Special Note on Subtraction (-): The minus sign can also convert positive numbers to negative numbers and negative numbers to positive numbers. x=-y is visual sugar for x=(y*-1). Special Note on Increment/Decrement (++/--): The double-plus and double-minus indicate the increment (or decrement) by one of the number. For instance.
var x = 5; x++; // x = 6; x--; // x = 5;
The increment/decrement operator can be either before the variable or after. If the operator is before the variable, the increment/decrement happens before anything else. If the operator happens after the variable the increment/decrement happens after everything else has been evaluated. For instance.
var x = 5; document.writeln(x++ +'<br>'); // Outputs: 5; document.writeln(x+'<br>'); // Outputs: 6; var x = 5; document.writeln(++x+'<br>'); // Outputs: 6; document.writeln(x+'<br>'); // Outputs: 6;
hunlock.com//The_Complete_Javascr
3/10
3/17/2011
Bitwise Operators
Bitwise operations are a bit of a hack in Javascript. Since all numbers in Javascript are floating point, and bitwise operators only work on integers, Javascript does a little behind the scenes magic to make it appear bitwise operations are being applied to a 32bit signed integer. Specifically, Javascript takes the number you are working on and takes the integer portion of the number. It then converts the integer to the most number of bits that number represents, up to 31 bits (1 bit for the sign). So 0 would create a two bit number (1 for the sign, and 1 bit for 0), likewise 1 would create two bits. 2 would create a 3 bit number, 4 would create a 4 bit number, etc It's important to realize that you're not guaranteed a 32bit number, for instance running not on zero should, in theory, convert 0 to 4,294,967,295, instead it will return -1 for two reasons, the first being that all numbers are signed in Javascript so "not" always reverses the sign, and second Javascript couldn't make more than one bit from the number zero and not zero becomes one. Therefore ~0=-1. So bitwise signs in Javascript are up to 32 bits. Operator & | ^ ~ << >> >>> Description AND OR XOR NOT Shift Left Shift Right Shift Right Notes 1&1=1,1&0=0 1|0=1, 0|0=0 1^1=0, 1^0=1 (Unary) ~1=0, ~0=-1 1<<2=4 -- shift 1, 2 bits left 4>>2=1 -- shift 4, 2 bits right (*) 4>>>2=1 -- shift 4, 2 bits right (*)
(*) When shifting right, double greater-thans (>>) will fill the new bits to the far left as 1s if the number was negative and zero if the number was positive. tripple greater-thans (>>>) is the same as double greater-thans but the fill bit will always be zero so the sign of the original number is not preserved and the result is always positive. With the exception of the bitwise NOT operator (~), all operators can be expressed as (operator)= when working with the same number as the variable.
x x x x x x = = = = = = x&5; x|5; x^5; x<<5; x>>5; x>>>5; // // // // // // is is is is is is the the the the the the same same same same same same as as as as as as x x x x x x &= 5; |= 5; ^= 5; <<= 5; >>= 5; >>>= 5;
One of the most common mistakes in Javascript is to use a bitwise operator in the place of a logical operator. For instance comparing two variables is expressed with the logical operator (&&), using a single & instead of a double && can yield unintended results. To avoid confusion you should always wrap bitwise operations in parenthesis to ensure it is not considered a logical evaluation!
parseInt(string[, radix])
hunlock.com//The_Complete_Javascr 4/10
3/17/2011
"parseInt" is one of the few global functions in Javascript, meaning it's not part of any core Javascript objects (save for the global object itself). This function accepts a string and converts it to an integer with a base of radix. For instance parseInt('ff',16) will return a value of 255. If no radix is specified parseInt will assume base 10. Be careful of leading zeros in your string! If the string begins with 0x the number is ASSUMED to be hexadecimal (base 16), and if the string begins with just 0, the number is ASSUMED to be octal if no radix is specified. For this reason it is recommended you ALWAYS specify a radix of 10 unless you specifically need another radix. parseInt performs no rounding, any digits after the decimal point (if any) are simply discarded. If the first character can not be converted to a digit parseInt will return NaN. parseInt will read from the first character to the first non-numerical character (not 01234567889).
document.writeln(parseInt('ff',16)+'<br>'); document.writeln(parseInt('09')+'<br>'); document.writeln(parseInt('09',10)+'<br>'); document.writeln(parseInt('123.85')+'<br>'); document.writeln(parseInt('0123.85')+'<br>'); document.writeln(parseInt('0123.85',10)+'<br>'); document.writeln(parseInt('$123.85',10)+'<br>'); document.writeln(parseInt('1,423.8',10)+'<br>'); document.writeln(parseInt('0x7',10)+'<br>'); document.writeln(parseInt('255',2)+'<br>'); document.writeln(parseInt('10',2)+'<br>'); // // // // // // // // // // // outputs: outputs: outputs: outputs: outputs: outputs: outputs: outputs: outputs: outputs: outputs: 255 0 (octal conversion) 9 (base 10 forced) 123 83 (octal conversion!) 123 (base 10 forced) NaN (Not a Number) 1 NaN (hex not base 10) NaN (Binary only 1 and 0) 2
parseFloat(String)
This function is similar to parseInt however it will correctly parse past the decimal point as well as accepting exponents. Unlike parseInt you can not specify a base or radix, the number will be pased as base 10 only. parseFloat performs no rounding. If the first character can not be converted to a digit, parseFloat will return NaN. parseFloat will read from the first character to the first non-numerical digit (not 0123456789.+-eE)
document.writeln(parseFloat('ff')+'<br>'); document.writeln(parseFloat('09')+'<br>'); document.writeln(parseFloat('09')+'<br>'); document.writeln(parseFloat('123.85')+'<br>'); document.writeln(parseFloat('0123.85')+'<br>'); document.writeln(parseFloat('$123.85')+'<br>'); document.writeln(parseFloat('1,423.8')+'<br>'); document.writeln(parseFloat('0xff')+'<br>'); document.writeln(parseFloat('3.14')+'<br>'); document.writeln(parseFloat('314e-2')+'<br>'); document.writeln(parseFloat('0.0314E+2')+'<br>'); document.writeln(parseFloat('3.14 is pi')+'<br>'); // // // // // // // // // // // // outputs: outputs: outputs: outputs: outputs: outputs: outputs: outputs: outputs: outputs: outputs: outputs: NaN 9 (No octal conversion) 9 123.85 123.85 (No octal conversion) NaN (Not a Number) 1 (, breaks the parse) 0 (No hex conversion) 3.14 3.14 3.14 3.14
3/17/2011
var value = 255 / 'greed'; document.writeln(isNaN(value)+'<br>'); var value = 255 / 0; document.writeln(isNaN(value)+'<br>'); document.writeln(value+'<br>'); var value = 255 / 'greed'; document.writeln((value==value)+'<br>');
NaN evaluates as FALSE in boolean expressions, however zero also evaluates as false so if you really want to avoid isNaN you can do a boolean evaluation as long as you also check for zero.
var value = 255 / 'greed'; if ( (!value) && (value!=0) ) { alert ('Value is not a number!'); }
Although literals are not objects, all of the methods in the Number object are available to literals because Javascript will temporarily copy numeric literals to an object in order to execute the desired method. Thus any prototypes you add to the Number object become available to all literal objects. The Number object itself, when not preceded by a "new" keyword will attempt to cast the first argument as a number which is useful for string conversions. If no conversion is possible Number will return the reserved word; NaN (not a number). Octal conversions happen only for literal constants and not on strings.
var var var var var x x x x x = = = = = Number('three'); Number('25'); Number('0377'); Number(0377); Number('0xFF'); // // // // // x x x x x = = = = = NaN (Not a number) 25; 377; (Not octal) 255; (Octal Conversion) 255; (Hex Conversion)
An additional quirk of the Number object is that the properites are available only through the Number object itself and not through child objects. Methods are available to all objects and literals.
var x = new Number(5); document.writeln(Number.MAX_VALUE+'<BR>'); // Returns: 1.7976931348623157e+308 document.writeln(x.MAX_VALUE+'<BR>'); // Returns: undefined. var x = 5; document.writeln(Number.MAX_VALUE+'<BR>'); // Returns: 1.7976931348623157e+308 document.writeln(x.MAX_VALUE+'<BR>'); // Returns: undefined.
3/17/2011
The following are the properties for the Number object. These properties are available ONLY to the Number object itself and not any children or literals. Property MAX_VALUE MIN_VALUE NaN NEGATIVE_INFINITY POSITIVE_INFINITY Notes Always the largest possible numeric value. Always the smallest possible numeric value. Value returned on Not A Number errors. Value returned on out of range negative numbers. Value returned on out of range positive numbers.
These properties are, effectively, constants. Importantly, they are a way to future-proof your Javascript. For instance, if, at some point in the future, Javascript migrates to 128 bit numbers instead of 64 bit numbers, the new minimum and maximum values will be reflected in MAX_VALUE and MIN_VALUE. If the error values of NaN or Infinity ever change they will be reflected in NaN, NEGATIVE_INFINITY, and POSITIVE_INFINITY. So wherever possible you should use these constants instead of hard coding the present values into your code. To test for NaN you should use the isNaN() function since NaN is always unequal to itself.
var x = Number('three'); if (x==Number.NaN) { alert('not a number!'); } var x = 28392838283928392*28392838283928392; if (x==Number.POSITIVE_INFINITY) { alert('out of range!'); } var x = -28392838283928392*28392838283928392; if (x==Number.NEGATIVE_INFINITY) { alert('out of range!'); } var maxNumber = Number.MAX_VALUE; var minNumber = Number.MIN_VALUE;
Firefox 1.5 Returns the expotential value of the number. Firefox 1.5 Returns a number with a specified number of decimals.
2.0 Displays the number using regional preferences. Firefox 1.5 Returns a string with a specified number of digits. Firefox 1.5 Returns the "source code" used to make the number.
hunlock.com//The_Complete_Javascr
3/17/2011
Number.toExponential([fractionDigits])
This method will return a string representation of the number as an exponent. If you provide a number in the first argument, this method will return only the specified number of decimal places.
var num=1232.34567; document.writeln(num+'<BR>'); document.writeln(num.toExponential()+'<BR>'); document.writeln(num.toExponential(1)+'<BR>'); document.writeln(num.toExponential(2)+'<BR>'); document.writeln(num.toExponential(3)+'<BR>'); document.writeln(num.toExponential(4)+'<BR>'); document.writeln(num.toExponential(5)+'<BR>'); document.writeln(num.toExponential(6)+'<BR>'); // // // // // // // // Outputs: Outputs: Outputs: Outputs: Outputs: Outputs: Outputs: Outputs: 1232.34567 1.23234567e+3 1.2e+3 1.23e+3 1.232e+3 1.2323e+3 1.23235e+3 1.232346e+3
If you are using a numeric literal (IE not a variable) then you should provide a space between the number and the method. If your number has no decimal you can also add one before calling the method.
document.writeln(1234..toExponential()+'<BR>'); //displays 1.234e+3 document.writeln(1234 .toExponential()+'<BR>'); //displays 1.234e+3
Number.toFixed([Digits])
This method attempts to return a string representation of the number as a non-exponent with [digits] numbers after the decimal. Its intention was to make it easier to work with Currency in Javascript, unfortunately it was introduced in Mozilla only with Firefox 1.5 and worse, IE 5.5 implemented a buggy version. IE 6 and Firefox 1.5 and higher can use this method reliably. For older versions you should provide your own methods. [Digits] can be a number from zero to twenty, if a number outside this range is passed toFixed will return a "RangeError". If no value is passed for [digits] a zero is assumed. The value is rounded up if the truncated digits evaluated greater than or equal to 5. So 123.456 would output 123.46.
var num=123.456789 document.writeln(num.toFixed()+'<br>'); // Outputs: 123 document.writeln(num.toFixed(0)+'<br>'); // Outputs: 123 document.writeln(num.toFixed(1)+'<br>'); // Outputs: 123.5 document.writeln(num.toFixed(2)+'<br>'); // Outputs: 123.46 document.writeln(num.toFixed(3)+'<br>'); // Outputs: 123.457 document.writeln(num.toFixed(4)+'<br>'); // Outputs: 123.4568 document.writeln(num.toFixed(5)+'<br>'); // Outputs: 123.45679 document.writeln(num.toFixed(6)+'<br>'); // Outputs: 123.456789 document.writeln(num.toFixed(7)+'<br>'); // Outputs: 123.4567890 document.writeln(num.toFixed(8)+'<br>'); // Outputs: 123.45678900 document.writeln(num.toFixed(25)+'<br>'); // Throws a range error exception.
Number.toLocaleString()
hunlock.com//The_Complete_Javascr 8/10
3/17/2011
This method is similar to toString([base]) with the exception that it attempts to format the number to meet the various regional preferences for displaying numbers. Unlike toString, toLocaleString() does not accept a base (so you can't specify base 16 to convert the number to hexadecimal).
var num=123.456789; document.writeln(num.toLocaleString()+'<BR>'); // Outputs: 123.456789
Number.toPrecision([precision])
This method will return a string with [precision] digits after the decimal point. Precision must be a value greater than 0. If no Precision value is passed, this method behaves like toString(). Like toFixed, this method will round up to the next nearest number.
var num=123.456789; document.writeln(num.toPrecision()+'<br>'); // document.writeln(num.toPrecision(1)+'<br>'); // document.writeln(num.toPrecision(2)+'<br>'); // document.writeln(num.toPrecision(3)+'<br>'); // document.writeln(num.toPrecision(4)+'<br>'); // document.writeln(num.toPrecision(5)+'<br>'); // document.writeln(num.toPrecision(6)+'<br>'); // document.writeln(num.toPrecision(7)+'<br>'); // document.writeln(num.toPrecision(8)+'<br>'); // document.writeln(num.toPrecision(9)+'<br>'); // document.writeln(num.toPrecision(10)+'<br>');// document.writeln(num.toPrecision(25)+'<br>');// Outputs: Outputs: Outputs: Outputs: Outputs: Outputs: Outputs: Outputs: Outputs: Outputs: Outputs: Outputs: 123.456789 1e+2 1.2e+2 123 123.5 123.46 123.457 123.4568 123.45679 123.456789 123.4567890 123.4567890000000005557013
Number.toSource()
Since Firefox version 1.5, all Javascript objects have a toSource() method which return the source-code equivalent of the object. This is extremely useful for creating JSON objects since you can easily turn objects, strings, arrays, and other data types into JSON data that can quickly be sent to the server. Unfortunately, only Firefox supports this method so its usefulness is limited only to office Intranets that have standardized on Firefox and volunteered to lock themselves into that platform for all time, no matter what).
var num=123.456789; document.writeln(num.toSource()); // outputs: (new Number(123.456789))
Number.toString([base])
The toString method outputs the number as a string. What is VERY useful and, more-often-than-not, overlooked is that you can pass the base or radix you would like the number to be displayed as. For instance passing a [base] of 16 will output the number as hexadecimal. A base of 8 will output the number as octal. A base of 2 will output the number as
hunlock.com//The_Complete_Javascr 9/10
3/17/2011
binary. (Note that this method will not place a leading zero in front of octal numbers or "0x" in front of hexadecimal numbers). If toString is passed without an argument, [base] will default to 10 (standard decimal).
var num=255; document.writeln(num.toString()+'<br>'); document.writeln(num.toString(16)+'<br>'); document.writeln(num.toString(8)+'<br>'); document.writeln(num.toString(2)+'<br>'); // // // // Outputs: Outputs: Outputs: Outputs: 255 ff 377 11111111
Number.valueOf()
This method simply returns the number as a string. Unlike the toString() method, valueOf does not allow you to base conversions. The string output is always equal to the number as it's represented in base 10.
var num=255; document.writeln(num.valueOf()+'<br>'); // Outputs 255
Sources
[1] comp.lang.javascript faqs
This article is copyright 2006, 2007 by Patrick Hunlock. The example code and concepts, unless otherwise noted, are released into the public domain and may be used and modified without compensation or attribution.
hunlock.com//The_Complete_Javascr
10/10