zoukankan      html  css  js  c++  java
  • The Complete Javascript Number Reference 转载自:http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference

    The Complete Javascript Number Reference

    Filed: 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.

    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) [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 Beyond

    If 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 Infinity and Infinity are equivalent. You can also test for infinity with the Number object's Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY property.

    result=2;
    for (i=1; result!=Infinity; i++){
       result=result*result;
       document.writeln(i+':'+result+'<BR>');
    }
    
    /* Outputs:
    1:4
    2:16
    3:256
    4:65536
    5:4294967296
    6:18446744073709552000
    7:3.402823669209385e+38
    8:1.157920892373162e+77
    9:1.3407807929942597e+154
    10:Infinity
    */
    

    Division by zero also generates an infinity result.

    document.writeln(255/0+'<br>');  // Outputs: Infinity
    document.writeln(-255/0+'<br>'); // Outputs: -Infinity
    

    Octal and Hexadecimal Numbers

    The 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 x (0x). This is only for the purpose of the initial evaluation, Javascript converts octal and hexadecimal numbers into base ten decimal as the script is evaluated.

    You should never precede a number with a zero unless you are specifically looking for an octal conversion!

    var octal = 0377;
    var hex = 0xFF;
    document.writeln('Octal: '+octal+'<br>');             // Outputs: 255
    document.writeln('hex  : '+hex+'<br>');               // Outputs: 255
    document.writeln('Octal=255 : '+(octal==255)+'<BR>'); // Outputs: true
    document.writeln('Hex=255   : '+(hex==255)+'<br>');   // Outputs: true
    document.writeln('Hex=0377  : '+(hex==0377)+'<br>');  // Outputs: true
    document.writeln('Ovtal=0xFF: '+(octal==0xff)+'<br>');// Outputs: true
    

    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

    +,-,*,/,% can also be expressed as +=, -=, *=, /=, %=.

       x = x+5; // is the same as x += 5;
       x = x-5; // is the same as x -= 5;
       x = x*5; // is the same as x *= 5;
       x = x/5; // is the same as x /= 5;
       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;
    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;
    

    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 Notes
    & AND 1&1=1,1&0=0
    | OR 1|0=1, 0|0=0
    ^ XOR 1^1=0, 1^0=1
    ~ NOT (Unary) ~1=0, ~0=-1
    << Shift Left 1<<2=4 -- shift 1, 2 bits left
    >> Shift Right 4>>2=1 -- shift 4, 2 bits right (*)
    >>> Shift 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&5;    // is the same as x &= 5;
       x = x|5;    // is the same as x |= 5;
       x = x^5;    // is the same as x ^= 5;
       x = x<<5;   // is the same as x <<= 5;
       x = x>>5;   // is the same as x >>= 5;
       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])

    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>');      // outputs: 255
    document.writeln(parseInt('09')+'<br>');         // outputs: 0 (octal conversion)
    document.writeln(parseInt('09',10)+'<br>');      // outputs: 9 (base 10 forced)
    document.writeln(parseInt('123.85')+'<br>');     // outputs: 123
    document.writeln(parseInt('0123.85')+'<br>');    // outputs: 83 (octal conversion!)
    document.writeln(parseInt('0123.85',10)+'<br>'); // outputs: 123 (base 10 forced)
    document.writeln(parseInt('$123.85',10)+'<br>'); // outputs: NaN (Not a Number)
    document.writeln(parseInt('1,423.8',10)+'<br>'); // outputs: 1
    document.writeln(parseInt('0x7',10)+'<br>');     // outputs: NaN (hex not base 10)
    document.writeln(parseInt('255',2)+'<br>');      // outputs: NaN (Binary only 1 and 0)
    document.writeln(parseInt('10',2)+'<br>');       // outputs: 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>');         // outputs: NaN
    document.writeln(parseFloat('09')+'<br>');         // outputs: 9 (No octal conversion)
    document.writeln(parseFloat('09')+'<br>');         // outputs: 9 
    document.writeln(parseFloat('123.85')+'<br>');     // outputs: 123.85
    document.writeln(parseFloat('0123.85')+'<br>');    // outputs: 123.85 (No octal conversion)
    document.writeln(parseFloat('$123.85')+'<br>');    // outputs: NaN (Not a Number)
    document.writeln(parseFloat('1,423.8')+'<br>');    // outputs: 1 (, breaks the parse)
    document.writeln(parseFloat('0xff')+'<br>');       // outputs: 0 (No hex conversion)
    document.writeln(parseFloat('3.14')+'<br>');       // outputs: 3.14
    document.writeln(parseFloat('314e-2')+'<br>');     // outputs: 3.14
    document.writeln(parseFloat('0.0314E+2')+'<br>');  // outputs: 3.14
    document.writeln(parseFloat('3.14 is pi')+'<br>'); // outputs: 3.14
    

    NaN - Not A Number

    If 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 Not a Number.

    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';
       document.writeln(isNaN(value)+'<br>');   // outputs: true
       var value = 255 / 0;
       document.writeln(isNaN(value)+'<br>');   // outputs: false 
       document.writeln(value+'<br>');          // outputs: infinity 
       var value = 255 / 'greed';
       document.writeln((value==value)+'<br>'); // outputs: false
    

    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!');
    }
    

    The Number Object

    For 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;
    var numericObject = new Number(0);
    if (numericLiteral) { } // false because 0 is a false value, will not be executed. 
    if (numericObject) { }  // true because numericObject exists as an object, will be executed. 
    

    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 x = Number('three');  // x = NaN (Not a number)
    var x = Number('25');     // x = 25;
    var x = Number('0377');   // x = 377; (Not octal)
    var x = Number(0377);     // x = 255; (Octal Conversion)
    var x = Number('0xFF');   // x = 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.
    

    The Number Object: Properties

    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 Notes
    MAX_VALUE Always the largest possible numeric value.
    MIN_VALUE Always the smallest possible numeric value.
    NaN Value returned on Not A Number errors.
    NEGATIVE_INFINITY Value returned on out of range negative numbers.
    POSITIVE_INFINITY 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;
    

    The Number Object: Methods

    There are only a few methods for the Number object most mathematical functionality has been moved to the Math object. The big catch with toExponential, toFixed, and toPrecision is that they are fairly modern constructs not supported in Mozilla until Firefox version 1.5 (although IE supported the methods since version 5.5). While it's mostly safe to use these methods, older browsers WILL break so if you are writing a public program it's recommended you provide your own prototypes to provide functionality for these methods for older browser.

    Method IE Version Mozilla Version Notes
    toExponential 5.5 Firefox 1.5 Returns the expotential value of the number.
    toFixed 5.5 Firefox 1.5 Returns a number with a specified number of decimals.
    toLocaleString 3 2.0 Displays the number using regional preferences.
    toPrecision 5.5 Firefox 1.5 Returns a string with a specified number of digits.
    toSource --- Firefox 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

    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>');                  // Outputs: 1232.34567
    document.writeln(num.toExponential()+'<BR>');  // Outputs: 1.23234567e+3
    document.writeln(num.toExponential(1)+'<BR>'); // Outputs: 1.2e+3
    document.writeln(num.toExponential(2)+'<BR>'); // Outputs: 1.23e+3
    document.writeln(num.toExponential(3)+'<BR>'); // Outputs: 1.232e+3
    document.writeln(num.toExponential(4)+'<BR>'); // Outputs: 1.2323e+3
    document.writeln(num.toExponential(5)+'<BR>'); // Outputs: 1.23235e+3
    document.writeln(num.toExponential(6)+'<BR>'); // Outputs: 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
    

    Supported since: IE 1.5, Firefox 1.5.

    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 aRangeError. 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.
    

    Supported since: IE 1.5, Firefox 1.5.

    Number.toLocaleString()

    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 
    

    Supported since: IE 3.0, Netscape 2.0

    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>');  // Outputs: 123.456789 
    document.writeln(num.toPrecision(1)+'<br>'); // Outputs: 1e+2
    document.writeln(num.toPrecision(2)+'<br>'); // Outputs: 1.2e+2
    document.writeln(num.toPrecision(3)+'<br>'); // Outputs: 123
    document.writeln(num.toPrecision(4)+'<br>'); // Outputs: 123.5
    document.writeln(num.toPrecision(5)+'<br>'); // Outputs: 123.46
    document.writeln(num.toPrecision(6)+'<br>'); // Outputs: 123.457
    document.writeln(num.toPrecision(7)+'<br>'); // Outputs: 123.4568
    document.writeln(num.toPrecision(8)+'<br>'); // Outputs: 123.45679
    document.writeln(num.toPrecision(9)+'<br>'); // Outputs: 123.456789
    document.writeln(num.toPrecision(10)+'<br>');// Outputs: 123.4567890
    document.writeln(num.toPrecision(25)+'<br>');// Outputs: 123.4567890000000005557013
    

    Supported since: IE 5.5, Firefox 1.5.

    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))
    

    Supported since: Firefox 1.5 (Firefox specific method).

    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 binary. (Note that this method will not place a leading zero in front of octal numbers or0x 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>');   // Outputs: 255
    document.writeln(num.toString(16)+'<br>'); // Outputs: ff
    document.writeln(num.toString(8)+'<br>');  // Outputs: 377
    document.writeln(num.toString(2)+'<br>');  // Outputs: 11111111
    

    Supported since: IE 3.0, Netscape 2.0

    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
    

    Supported since: IE 3.0, Netscape 2.0

  • 相关阅读:
    MySQL导出数据到文件中
    MySQL表内更新时,自动记录时间
    MySQL实现分页查询
    shell 中执行Oracle查询和执行存储过程
    python调用其他脚本
    hadoop 中ALL Applications 中Tracking 下History查找不到MapReduce Job 日志
    Matplotlib 随机漫步图
    Matplotlib 绘图
    shell中$(( ))、$( )、``与${ }的区别详解
    jquery动画切换引擎插件 Velocity.js 学习01
  • 原文地址:https://www.cnblogs.com/prettyisshit/p/3860719.html
Copyright © 2011-2022 走看看