There are several ways to declare a number in JavaScript
5
3.1415
9e+4
0xfff
Furthermore, there are a handful of common arithmetic operators available in JavaScript.
To convert a number to a string, you can either use the parseInt()
or parseFloat()
method, depending on whether you want to truncate the decimal point.
parseInt('22') // 22
parseFloat('3.14'); // 3.14
parseFloat('23.4 hahahahahlololol'); // 23.4
In the last example, only the first number in the string is parsed. If there are no values at the beginning, you'll get a NaN
data type.
These methods can be used with any number value.
var sampleNum = 5;
sampleNum.toPrecision(4); // 4.000
sampleNum.MAX_VALUE; // 1.7976931348623157e+308
The Math object contains a library of parameters and functions related to number generation and manipulation. To call it, call the Math variable, and either its attributes or a function.
Here are some common constants that are stored as attributes in the Math object:
Furthermore, the Math object contains a number of functions for complex calculations.
Math.min(1, 4, 5); // 1
Math.floor(1.242); // 1
Math.isNaN(21); // false
We'll soon cover objects, but for now just use this notation to access Math's attributes and functions.
To generate random numbers, use the Math.random()
function. This will return a value from 0 up to 1.
Thus we can get a random number between 1 and 100 with the following code:
var randomNum;
randomNum = Math.floor((Math.random() * 100) + 1);
The dot notation is called so because it uses the period (or the dot) to access an object's methods and properties. As you will (or have) seen in many other programming languages, the dot notation provides a clean way to access the members of an object.
This book was written for anyone who wants to use JavaScript to make their websites a little more interesting, engaging, interactive, or usable. In particular, it is aimed at people who do not have a degree in computer science (well, not yet anyway).
$ Check priceRelieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.
$$ Check priceAd