The JavaScript Programming Language
Numbers
There is no difference between float and integer. JS have only number type.
Number is 64-bit floating point value what means ±1.7976931348623157 × 10308 for big numbers and ±5 × 10−324 for small numbers.
Integers can be represented between −9007199254740992 (−253) and 9007199254740992 (253)
Integer literals
//base 10
0, 15, 100000
//base 16 (hexadecimal)
0xff , 0xCAFE911
//base 8 (octal) - not standard
065
Never use preceeding zero when defining decimal integer because octal numbers uses that.
Converting decimal into hexadecimal: 010number_DecToHex.js
Converting hexadecimal to decimal: 011number_HexToDec.js
Floating-point literals
Floating numbers have decimal point.
3.14159
2.34e12 //exponential with small e
2.34E12 //exponential with big E
2.34e-2 //negative exponent
//converting number to exponential format: 012number_toExponential.js
var n = 1258;
var exp = n.toExponential();
console.log(typeof exp); //string
console.log(exp); //1.258e+3
Arithmetic and operators
Basic operators are: + - * / and %
Usage of modulo operator % : 013number_modulo.js
Also in calculation Math object can be used
Math.pow(8,2) //64
Math.round(1.2) //1
Math.ceil(0.6) //1 round up to an integer
Math.floor(.6) //0 round down to an integer
Math.abs(-5) //5
Math.max(x,y,z) //maximal number
Math.min(x,y,z) //minimal number
Math.random()
Math.PI
Math.E
Math.sqrt(3)
Math.sin(0)
Math.log(8)
Infinity
Division by zero returns Infinity or -Infinity. Infinity has number type. Example: 014number_division_by_zero.js
Infinity can be defined by: 016number_infinity.js
var pi = Number.POSITIVE_INFINITY;
var ni = Number.NEGATIVE_INFINITY;
var inf = -Infinity;
isFinite() - check if the number is finite: 017number_isFinite.js
isFinite() returns true if its argument is a number other than NaN, Infinity, or -Infinity.
Underflow
In JS number is zero when it is smaller then ±5 × 10−324 . This is called underflow.
var y = -2e-324; returns negative zero : 019number_negative_zero.js
NaN
Nan occurs when we try to perform math operation on non number, for example on string. NaN has number type. There is no -NaN.
NaN cases
y = 0 / 0;
x = parseInt('asas', 10);
z = Math.sqrt(-3);
isNaN() - check if the result is NaN: 018number_isNaN.js
Float point rounding error
In JS 0.3 - 0.2 returns 0.09999999999999998 , and 0.2 - 0.1 returns 0.1. That's why we can't compare those two results.
Rounding error example: 020number_float_rounding_error.js
This error can be corrected by:
var z = 0.5 - 0.4; //0.09999999999999998
z = parseFloat(z.toPrecision(12)); //0.1