|
網誌存檔
熱門網志
|
|
The Complete Javascript Number ReferenceFiled: Mon, Apr 30 2007 under Programming|| Tags: reference javascript numbers number math Javascript is not a typed language so it should come as no surprise that there are no specific integer or floating-point types, no short, long, byte, double, or any other type other languages use to define numbers. 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). This reference will cover Javascript numeric literals and objects as well as the default Javascript Operators which manipulate those numbers. PrecisionAll 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) [1]. 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. To Infinity And BeyondIf you attempt to work with numbers outside of the generous range provided by Javascript, Javascript will return a special constant of either -Infinity or Infinity, representing a negative or positive overflow, respectively. [-]Infinity is a special reserved keyword in Javascript like NaN (not a number), or undefined. It can behave as both a value or a string, that is result=2; Division by zero also generates an infinity result. document.writeln(255/0+`<br>`); // Outputs: Infinity Octal and Hexadecimal NumbersThe ability of Javascript to handle Octal and Hexadecimal numbers is a relatively new feature of the language and so it`s not universally supported. However, as each day passes this ability becomes more and more reliable as older browsers are upgraded. If you are coding for a corporate Internet where you can ensure a base version level (Firefox 1.5 or higher, IE 5.5 or higher) this functionality should be considered safe. Numeric constants are considered octal if they are preceded by a zero, and are considered hexadecimal if they are preceded by a zero and and You should never precede a number with a zero unless you are specifically looking for an octal conversion! var octal = 0377; Since Javascript stores all numbers as base ten decimals, you`ll need to use the var num=255; Arithmetic Operators
+,-,*,/,% can also be expressed as +=, -=, *=, /=, %=. x = x+5; // is the same as x += 5; 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; 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; 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; Bitwise OperatorsBitwise 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 So bitwise signs in Javascript are up to 32 bits.
(*) 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&5; // is the same as x &= 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])
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>`); // outputs: 255 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>`); // outputs: NaN NaN - Not A NumberIf Javascript is unable to perform an operation on a number, many Javascript methods and operators will return NaN, a special reserved word indicating the result was NaN is always unequal to all other numbers and itself. If you would like to make sure the result was a number and not the NaN error condition use the isNaN(value) function. var value = 255 / `greed`; 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`; The Number ObjectFor consistancy, Javascript provides a Number object. For the most part, you will not need to define numbers as objects and there are quite a few reasons why you should not use numbers as a Number object. For instance… var numericLiteral = 0; 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 var x = Number(`three`); // x = NaN (Not a number) 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); The Number Object: PropertiesThe following are the properties for the Number object. These properties are available ONLY to the Number object itself and not any children or literals.
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`); |
-------------------------------------------------
| 上一篇:Essential Javascript -- A Javascript Tutorial | 下一篇:The Complete Javascript Strings Reference |

