# JavaScript Numbers – Get Skilled in the implementation of its Methods!

Free Web development courses with real-time projects Start Now!!

We use numbers to count, measure and label. We’ve been learning about them since playschool and we still use them as adults. We deal with numbers in our everyday life, may it be our finances, our scores or some calculations. They never leave our side, whether we like it or not. Thus it isn’t possible that we learn JavaScript without learning about numbers.

Going forward in our journey of JavaScript DataFlair Tutorial Series, this article will focus on all the aspects of JavaScript Numbers. We will learn the different methods to write a number and convert data types into numbers in JavaScript. But before that, we would strongly recommend you to go through our previous tutorial on * JavaScript Boolean*. It will help you in better understanding of the concept.

After knowing what JavaScript Booleans are, let’s start with the tutorial on JavaScript Numbers.

## What are JavaScript Numbers?

The number type in JavaScript represents *integers, floating-point-values, hexadecimal, octal and exponential values*. The script stores all the JavaScript numbers in **64-bit** format IEEE-754 standard, also called **“double-precision floating-point numbers”**. The number is stored in memory in the following manner:

**Value**: 52 bits (0-51)**Exponent**: 11 bits (52-62)**Sign**: 1 bit (63)

### Different Methods to Write a Number in JavaScript

There are various approaches to write a number in JavaScript. Some of them are explained below with examples:

**1. For Large Numbers**

Suppose you are working on a JavaScript application for a bank’s database management. There are millions of numbers you need to wade through and not all of them are small. Imagine having to write **₹10,00,000** for every transaction of **10 lacs**. And you can’t even insert any commas between the numbers, so keeping track of the numbers is almost impossible and if tracked, it’s a tedious process, isn’t it? Also, it creates opportunities for serious errors that you can’t afford. We prefer to write** 10 lacs** and guess what, we can help JavaScript do that too! We can also shrink and represent the time required to finish the transactions, say** 0.002** **seconds**, making our application a lot more efficient.

You can shorten the number by simply appending the letter **“e”**, followed by the number of zeroes after it. Let’s use this technique to test different values in the browser console.

var million = 1e6; //1 and 6 zeroes (one million) var milliseconds = 2e-3; //5 zeroes to the left from 2

**Output:**

**2. hex, octal and binary numbers**

Hexadecimal numbers are very common to represent *colors, memory locations, encode characters, etc.* JavaScript supports octal and binary numbers, though not as widely used. The short number representation of *hex, octal and binary numbers* are the prefixes **0x, 0o** and **0b** respectively, followed by the number.

var decimal = 157 // decimal number 0x9D //hexadecimal number 0o235 //octal number 0b10011101 //binary number

**Output:**

**3. The parseInt() and parseFloat() methods**

The **parseInt()** and **parseFloat()** methods in JavaScript provide the programmer with the facility to extract the numeric values from a given value. In every transaction, the time required is in form **2ms (0.002 seconds)**. But to perform the needed calculations, we have to separate the value from the unit. For an efficient banking application, it is essential since we work on the actual numbers, excluding the unit.

The **parseInt()** and **parseFloat()** methods help us to achieve this task by extracting integers and floating-point numbers from the given value. The methods do it by reading the value, from left to right. While the **parseInt()** method returns the integer and stops reading the value after getting a non-number value, the** parseFloat()** method continues its work even after the first point. It then returns the floating-point value (with a single point) and skips everything after the floating-point data it needed.

The syntax for the **parseFloat()** method is as follows:

parseFloat(string)

The syntax of the parseInt() method looks like this:

parseInt(string, ?radix)

Why the second parameter? The optional parameter** (radix)** specifies the base of the numeral system, allowing us to extract numeric data from values with different bases too.

Let us see these methods in action; open up your console and get started with the code below.

var time = '2e-3s' parseFloat(time) //time in seconds // 0.002 parseInt(time) //time in milliseconds // 2 parseInt('9d', 16) //extracting the number's base 16 equivalent // 157 parseInt(0o34, 17) //extracting base 17 equivalent of octal number // 42 parseInt('ff', 8) //out of the range of octal number // NaN

**Output:**

Notice that we extracted the hex and octal methods with different specifications. We ignored **0x** with **9d**, but still got the expected result. When we tried to do the same with** base 8**, we got NaN. This is because numbers with **base 8** don’t recognize the string as a **hex** number. You need to use **0xff** in its place if you want to find its value.

### Adding Strings and Numbers

JavaScript **+ operator** works as both an arithmetic and string (concatenation) operator. When we add two or more numbers, we get the sum. But the moment a string enters the equation, concatenation operator comes into play. After the script encounters a string, it uses concatenation operator even for numbers. This is clear from the last statement in the program below. We expected **1 + 2 + “4” + 2 + 1** to produce the result **343** but got **3421**.

**Don’t forget to explore our tutorial on JavaScript Strings**

1 + 2 //arithmetic operator // 3 //concatenation operator "4" + 1 // 41 1 + '2' // 12 //combining arithmetic and concatenation operators 1 + 2 + "4" + 2 + 1 // 3421

**Output:**

### Imprecise Calculations

**Problem1:**

Since the number is represented in **64-bit format**, internally, there are exactly 64 bits available to store a number. If a number exceeds this storage limit, we get an Infinity. This will cause errors and crash our application.

**Problem2:**

Another problem we might face while dealing with numbers is the loss of precision. It isn’t always obvious but happens quite a lot.

Let’s first understand what I mean with the two problems above by testing the following code in the browser console.

4e786 //problem1 // Infinity 1.6 + 0.8 //problem2 // 2.4000000000000004 1.6 + 0.8 = 2.4 //false

**Output:**

Okay, that wasn’t what we expected, was it? We expected the result of **1.6 + 0.8** to be** 2.4**. And though close, it isn’t the same; this will cause havoc in our programs. This is the reason we got **false** when compared with the expected result.

Now you might be wondering why this happened and how to resolve it. We got an imprecise result of our calculations because fractions like **1.6** and **1.8** are unending in their binary form. Think of the value of **pi (22/7)**: it goes on forever. But we use **3.14** for its value by rounding it to two digits and the same is possible for JavaScript numbers.

We use the JavaScript **toFixed()** method to solve the dilemma. The syntax of this method is as follows:

number.toFixed( ?precisionValue)

The parameter of this method specifies the precision i.e. number of figures on the right of the decimal. This method always returns a string, so to get a number, we can use a unary plus at the beginning.

**Learn to implement the unary plus and several other JavaScript Operators**

Test the following code in the console:

var pi = 22/7 pi.toFixed(10) // "3.1428571429" var sum = 1.6 + 0.8 sum.toFixed(2) // "2.40" +sum.toFixed(2) // 2.4

### isNaN() and isFinite() methods

**NaN (Not-a-Number)** is a keyword (reserved word) in JavaScript implying that the value is not a legal number. If you try to perform numeric calculations on non-numeric data values, the script returns **NaN**. However, in terms of strings with a numerical data value, we don’t get a NaN due to type-casting. The **typeof operator** tells us that the NaN is a numeric data type.

We can check if the value we get is a JavaScript number or not with the help of **the isNan() method**. It returns a Boolean value, depending on whether the value is a number **(false)** or not **(true)**. The code below implements the concept of NaN in the console.

*Note: NaN === NaN returns false because the value of NaN is not equal to anything, including itself.*

num1 = 120 / "DataFlair" // NaN num2 = 120 / "10" //type-casting // 12 isNaN(num1) // true isNaN(num2) // false isNaN() // true typeof NaN // "number"

**Output:**

In the topic above, we encountered **Infinity** for larger numbers. We don’t want our program to return this value until we specifically mention it. The script returns **Infinity** (or **-Infinity**) when you try to calculate a number outside the range of JavaScript numbers. The **typeof** **operator** returns **‘number’ for Infinity.**

Using the **isFinite()** method, we can check if a number is a regular number (returns true) or **NaN, Infinity or -Infinity** (returns **false**).

Try the following code in your console window to verify what we’ve discussed about Infinity.

typeof Infinity // "number" isFinite(NaN) // false isFinite("DataFlair") // false isFinite(14) // true isFinite(Infinity) // false isFinite() // false

**Output:**

**Hold On! Did you check the article on JavaScript Objects?**

### The Number Object

The** Number** object is a wrapper object that works with numerical data values. Until now, we worked with numeral literals** (var number = value**), but we can create a **Number object** with the **Number() constructor**. The syntax of creating a Number object is as follows:

var num = new Number(value);

### Properties of Number Object

The following are the properties associated with a Number object:

Property | Description |

MAX_VALUE | It is the largest positive representable number. |

MAX_SAFE_INTEGER | It represents the largest safe integer number (253 – 1). |

MIN_VALUE | It is the smallest positive representable number i.e. the number closest to zero without actually being zero. |

MIN_SAFE_INTEGER | It represents the smallest safe integer number (-(253 – 1)). |

NaN | It equals to a special value that is “not a number”. |

POSITIVE_INFINITY | It is a special value representing infinity, returned on overflow. |

NEGATIVE_INFINITY | It is a special value representing negative infinity, returned on overflow. |

The program below implements the different Number properties that we discussed.

Number.MAX_VALUE // 1.7976931348623157e+308 Number.MAX_SAFE_INTEGER // 9007199254740991 Number.MIN_VALUE // 5e-324 Number.MIN_SAFE_INTEGER // -9007199254740991 Number.NaN // NaN Number.POSITIVE_INFINITY // Infinity Number.NEGATIVE_INFINITY // -Infinity

**Output:**

### JavaScript Number Methods

The table below lists all the methods you need to focus on.

Method | Description |

toExponential(?fractionDigits) | It returns the exponential value as a string. |

toPrecision(?precision) | It returns the number as a string with precision digits in total. |

toString(?radix) | It returns the string representation of the object in the specified radix. |

valueOf() | It returns the primitive value of the specified object. |

isInteger() | It determines whether the value passed is an integer or not. |

isSafeInteger() | It determines whether the value passed is a safe integer or not. |

Let’s implement these methods in the console window.

num = 250 // 250 num.toExponential() // "2.5e+2" num.toExponential(2) // "2.50e+2" num.toPrecision(5) // "250.00" num.toString(17) // "ec" num.valueOf() // 250

**Output:**

### Converting different Data Types to Numbers

The following code in your browser console window will convert different JavaScript values into a Number object.

Number() // 0 Number("") // 0 Number("12") // 2 Number("12.50") // 12.5 Number("125e-2") // 1.25 Number(null) // 0 Number("null") // NaN Number(0xff) // 255 Number(0o150) // 104 Number(0b110) // 6 var date = new Date() date // Fri Jul 26 2019 14:25:45 GMT+0530 (India Standard Time) Number(date) // 1564131345705

We also used the **Date** object in the last three statements. We will discuss what they are and how they work in the next tutorial of this series.

**Output:**

## Summary

Here we come to the end of our tutorial on JavaScript Numbers. In this article, we took a brief look at the concepts of numbers in JavaScript, various approaches to write a number in JavaScript and different terminologies attached to it. We also learned about JavaScript Number object.

**Next, you must go through our tutorial on JavaScript Date and Time**

Hope you liked our article. Don’t forget to share your views through the comment section below.

**Did you like this article?
If Yes, please give DataFlair 5 Stars on Google **