75% developed

Common JavaScript Manual/Data types - Numbers

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Numbers[edit | edit source]

For example, let's set the value for the variable 'a'

a = 46;

And for the variable 'b'

b = 7;

Arithmetic operations[edit | edit source]

Let's output results of arithmetic operations with these variables.

print(a + b);
print(a - b);
print(a * b);
print(a / b);
print(a % b); //Modulo

Increment, Decrement, Unary operators[edit | edit source]

For enlarging or reducing some variable by one we can use increment and decrement operator. And we can change char of number by unary operator. Decrement and increment have two types of recording - postfix and prefix. Prefix - first the value is changed then the new value is returned. Postfix - first the value is returned then value is changed.

a = 5;
b = ++a; // b = 6 , a = 6
b = a--; // b = 6 , a = 5
b = -a; // b = -5

Standart library functions[edit | edit source]

Also we can apply some functions to numbers. We will consider only most important.

c = f.toFixed(b); //Rounding to 'b' digits after  dot
d = Math.abs(-6); //Absolute value (module) of number
e = Math.round(f); //Rounding to integer
g = Math.max(a,b); //Maximum value of variables 'a' and 'b'
h = Math.min(a,b); //Minimum value of variables 'a' and 'b'
k = Math.pow(a,b); //Variable 'a' in power 'b'
t = Math.sqrt(a); //Square root of variable 'a'
w = Math.random(); //Random number from 0 to 1

Standart library constants[edit | edit source]

Standart library include some math constants. We will consider only the most important.

a = Math.PI // π number
b = Math.E // e number

Special values[edit | edit source]

Numbers in JavaScript also include two special values are Infinity and NaN(Not a Number)

a = 1/0 // Infinity
b = Math.sqrt(-1) // NaN

Data types - Arrays