3. Data Types
3.2. Numbers
A numerical value is a number.
As strings do, numbers are not associated with any special syntax. If you were to quote 5
(β5β), it would be a character in a string, not a number. It can be a decimal (float) or a whole and it
can have positive or negative value.
var x = 5; // whole integer
var y = 1.2; // float
var z = -76; // negative whole integer
Number can be up to 15 digits.
var largeNumber = 999999999999999; // a valid number
How to write scientific notation in JavaScript?
- e-notation indicates a floating-point value.
- E-notation displays a number raised to a given control that should be multiplied by 10.
- In JavaScript, the format of e-notation is to have a number, integer or floating-point, followed by e or E, then by the power to multiply by 10.
Example:
var floatNum = 7.215e7; //equal to 72150000 document.write(floatNum);
In this case, 72,150,000 is equal to floatNum. In short, the notation states, "Take 7.215
and multiply it by 10^7."
With numbers: addition (+), subtraction (-), division (/) and multiplication (+), you can do
regular math.
var sum = 2 + 5; // displays 7
var difference = 6 β 4 // displays 2
With variables, you can do math like the example below:
- <!DOCTYPE html>
- <html>
- <body>
- <h2>Variables of JavaScript</h2>
- <script>
- var score1 = 3;
- var score2 = 7;
- var score3 = 9;
- var score4 = 1;
- var TotalScore = score1+score2+score3+score4; //displays 20
- document.write(TotalScore);
- </script>
- </body>
- </html>
Two uncommon number type:
While theoretically itβs a type of number, NaN means Not a Number. NaN is the product of
attempting to do arithmetic with other data types.
var notNum = 5 / "Five" // results NaN
For instance, dividing a number by a string will result in NaN.
Technically, Infinity is a number, either the answer of dividing by 0 or calculating a number too large.
var endless = 1 / 0; // results Infinity