var x = 3.14; // A number with decimalsvar y = 3; // A number without decimals
JavaScript Numbers are Always 64-bit Floating Point
Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.
JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.
This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:
This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:
Precision
Integers (numbers without a period or exponent notation) are accurate up to 15 digits.
var x = 999999999999999; // x will be 999999999999999var y = 9999999999999999; // y will be 10000000000000000
Adding Numbers and Strings
WARNING !!
JavaScript uses the + operator for both addition and concatenation.
Numbers are added. Strings are concatenated.
var x = 10;
var y = 20;
var z = x + y; // z will be 30 (a number)
var y = 20;
var z = x + y; // z will be 30 (a number)
The JavaScript compiler works from left to right.
First 10 + 20 is added because x and y are both numbers.
Then 30 + "30" is concatenated because z is a string.
var x = 100; // x is a number
var y = "100"; // y is a string
var y = "100"; // y is a string
NaN - Not a Number
NaN is a JavaScript reserved word indicating that a number is not a legal number.
Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):
var x = 100 / "Apple"; // x will be NaN (Not a Number)
Infinity
Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.
var myNumber = 2;
while (myNumber != Infinity) { // Execute until Infinity myNumber = myNumber * myNumber;
}
while (myNumber != Infinity) { // Execute until Infinity myNumber = myNumber * myNumber;
}
Hexadecimal
JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.
var x = 0xFF; // x will be 255
0 comments:
Post a Comment