Subtypes

Numbers in programming can either be integers or floats (decimals).

In JavaScript, unlike some other programming languages like C#, Java, we have only one type for all kinds of numbers and that type is number.

All numbers in JavaScript return "number" when inspected using the typeof operator.

However this doesn't mean that a programmer should not bother to know what are the two kinds of numbers in programming - integers and floats - especially considering the fact that some methods use these respective names.

So let's first understand the difference between these two sub-types.

Integers

Integers are numbers that don't contain decimals. They can range from -Infinity to +Infinity including zero. Therefore -10, -3, -1, 0, 5, 320, 18501 are all examples of integers whereas -10.3, 0.55 and 5.11 aren't

Floats

Floats or floating numbers or floating-point numbers are numbers that contain decimal values like 10.1, 10.3, 10.5. They are useful in currency math, statistical math, co-ordinate geometry etc and other places where integers would completely mess up with the precision of the calculations.

Examples

Let's see some actual numbers in JavaScript:

var num = 10; // an integer
num = 10.5 // a float

One common symbol used in representing numbers is e. Numbers that include this symbol are commonly known to be in the exponential form.

The way the symbol works is shown as follows:

var num = 1e2; // 100
num = 1.45e5; // 145000

As you may have guessed, the number preceding e is multiplied by 10 to the power of the number following the symbol e.

1e2 likewise means 1 x 102, 1.45e5 means 1.45 x 105, and so on and so forth.

The number following e is called the exponent. Hence, the exponent is 2 in 1e2, and 5 in 1.45e5.

Negative exponents are also valid:

var num = 505e-2; // 5.05
num = 1.62e-5; // 0.0000162

Special numbers

Apart from the real numbers we've just seen, there are also some special types of numbers in JavaScript as we shall discover in this section.

Infinity

As the name suggests, Infinity is used to represent the result of any arithmetic operation that is beyond the scope of calculation in JavaScript math.

For example, dividing 1 (or any other number) by 0; or raising 2 to the power of 50000 will yield Infinity.

This is because both these operations are practically not possible to be calculated:

  1. 1 / 0 is a classic operation in mathematics that yields the symbol
  2. 2 ** 50000 is simply not accomodable in the space allocated to each number in JavaScript.

One common use of Infinity is in programs that require comparison with an extremely high value, such as in determing the maximum value from a group of numbers.

Consider the code below:

var max = Infinity;

Note that Infinity is a special keyword - it doesn't has any quotes around it.

If you're thinking about a corresponding minimum value, then just hold on - adding a minus sign in front of Infinity makes it the smallest of all possible values.

Consider the following code:

var min = -Infinity;

Here we've prefixed the Infinity keyword with a minus sign to make it the least possible value.

When using Infinity in calculations remember that it is not a string and therefore can't be written like "Infinity"!
Remember that Infinity is case-sensitive!
Whatever you add to or subtract from Infinity, the final result will always be Infinity

NaN - Not a Number

The second special number is NaN which stands for Not a Number.

All calculations that can't be computed, even in terms of Infinity, are tagged as NaN.

Examples include taking the square root of a negative number; dividing a number by an object; converting alphabetical text to number; and so on and so forth.

Including NaN in an expression yields NaN as the final result.

Following is an illustration:

Math.sqrt(-10); // NaN
Number("Hello"); // NaN

NaN + 0; // NaN
NaN - 10; // NaN
10 + 50 * NaN; // NaN
10 * 50 + NaN; // NaN

Unlike Infinity, NaN is not directly of any use.

Checking for special numbers

If we want to check whether a given number is NaN or Infinity, we can use two dedicated methods to accomplish this.

They are isNaN() and isFinite() respectively.

The method isNaN() takes an argument and return true if it's NaN, or else the value false.

Similarly, isFinite() also takes an argument and returns true if it's not Infinity, or else the value false.

The code below illustrates both the methods on a couple of numbers:

isFinite(2 ** 10000) // false
isFinite(2) // true

isFinite(Infinity) // false
isFinite(-Infinity) // false

isFinite(NaN) // false
isNaN(2) // false

isNaN(Infinity) // false
isNaN(Infinity - Infinity) // true

isNaN(NaN) // true
Infinity - Infinity returns NaN, and likewise isNaN(Infinity - Infinity) returns true.

Converting to number

Often times while developing a program, we may want to convert a value of given data type to a number. Let's suppose that we want to go from a string to a number.

Number()

In this case we can simply use the Number() function.

Number() converts its given argument into a number.

Say we want to convert the string "10" into a number. The following code demonstrates how to do that:

var str = "10"; // a string
var num = Number(str); // num is 10, not "10"

console.log(typeof num); // returns number

Here str acceptably could've been "10.5", "2.512" and even "1e5". Notice that in all these strings we have actual number representations and nothing non-numerical.

Whatever counts as an invalid number, would be converted to NaN by Number().

Consider the following code:

var str = "10 ants"; // a string containing a number and some text
var num = Number(str); // num is NaN

Notice str here - it contains some non-numerical text "ants", and is therefore not entirely a number. Likewise, it gets converted to NaN (Not a Number)!

Similarly all the following variants of str would work the same way - "10a", "10.5 NaN", "1e5x", "10 / 5".

console.log(Number("10a")); // NaN
console.log(Number("10.5 NaN")); // NaN
console.log(Number("1e5x")); // NaN
console.log(Number("10 / 5")); // NaN
Even valid mathmetical expressions don't count as a valid number! This is the reason why line 4 also logs NaN.

In short, Number() is ideal for cases where we need to just convert a stringified number into an actual number.

For cases, where some other pieces of text are connected with the stringified number as in "10 ants", we ought to use more powerful conversion mechanisms i.e parseInt() and parseFloat().

The Number() function can not just convert strings to numbers but all data types to numbers. Try experimenting it out with different values (booleans, arrays etc.) and draft the rules, this time on your own!

parseInt()

To parse an integer out of a given string use the parseInt() function.

Unlike Number(), this function is a bit more intelligent in extracting out a number from a given string.

It reads a string and extracts only the numeric part out of it. However note that the numeric part shall appear before any strings, otherwise parseInt() will also return NaN.

Moreover, the results of parseInt() can be strange in many occasions, such as when used on strings such as "1e5".

parseInt(x)
Where x is the value that is to be converted to an integer number.

Here's a simple example:

var str = "10 ants";
var num = parseInt(str);

console.log(num); // 10

And following is an array of examples:

console.log(parseInt("105.9")); // 100
console.log(parseInt("2e5")); // 2

// here some text appears before any number,
// likewise the result is NaN
console.log(parseInt("Ants are 10")); // NaN
parseInt() only entertains whole numbers before the decimal point, or the e symbol. This means that parseInt("9.9") and parseInt("9e5") would both return 9.

One crucial thing to note is that parseInt() first converts its argument into a string and then parses it. This means that passing in the number 10.2 is the same as passing in the string "10.2".

In the following snippet, we parse a couple of data types into number using parseInt():

console.log(parseInt(1e5)); // 10000
console.log(parseInt(1e50)); // 1

console.log(parseInt(false)); // NaN
console.log(parseInt(true)); // NaN

console.log(parseInt([10, 30])); // 10

In line 1, we call parseInt(1e5) which returns 10000, however in line 2 a similar expression parseInt(1e50) returns 1.

This might look confusing.. but really it isn't!

Recall that parseInt() converts its argument into a string before it carries on with the parsing process.

The number 1e5 is represented as 10000 in numeric format, which simply gets converted to the string "10000", interally by parseInt(). This string is then parsed into the number 10000.

On the other hand, 1e50 is represented as 1e50 in numeric format, and therefore converts to "1e50". This string is parsed into 1.

parseFloat()

Heard of a similar name? What do you think would this function do? It would simply convert string values to floating numbers.

parseFloat(x)
Where x is the value that is to be converted to an floating number. x can be a number or a string in its literal form or object form (using the Number() or String() constructors respectively)
var str = "10.9187" // typeof string;
var num = parseFloat(str) // typeof number;
The parseFloat() function removes insignificant digits after the decimal point. Therefore parseFloat(10.00000000) would return 10.
Operation expressions inside strings like "10 / 5" or "10 + 5" aren't entertained by any of the methods above..

Conclusion

After reading this chapters you can see that numbers - integers and floats - really play a vital role in programming but much of this role depends upon functions, as you just saw, and methods that you will see in the next chapter.