How numbers are stored in JavaScript ?
Last Updated :
22 May, 2023
In this article, we will try to understand how numbers are stored in JavaScript. Like any other programming language, all the data is stored inside the computer in the form of binary numbers 0 and 1. Since computers can only understand and process data in the form of 0’s and 1’s.
In JavaScript, there is generally only a Number as a primitive data type but the numbers are of the form Integer and float. So these types come under the Number data type and are internally stored according to their different formats depending upon the type of operation being performed on them.
Let us now understand how different numbers are stored in JavaScript.
Storing of Integer Numbers
Integer: These numbers are further divided into two types
- Signed Integers
- Unsigned Integers.
To store unsigned integers simple binary format is used.
Below are a few examples of how different unsigned integers are stored in JavaScript.
let a = 4
let b = 78
a will be stored in the memory with the value of:- 100
b will be stored in the memory with the value of:- 1001110
Note: This method fails when working on unsigned integers as extra data is required to store the sign of numbers.
There is a convention to store the leftmost bit as a sign bit and use 0 for positive and 1 if negative number.
This method is known as Signed Magnitude
The below example illustrates how we will store the number in Signed Magnitude format.
let a = 6
let b = -6
a will be stored in memory with the value of :- 000110
b will be stored in memory with the value of :- 100110
A problem arises when we try to perform addition on these two values. the addition performed on the binary numbers returns
100110 + 000110 = 101100 // 44
We should get 0 when we add the two numbers but instead, we get 44
A further improvement of this method was implemented and one’s complement representation was used to store the number
One’s complement of a number is toggling all the 0’s into 1 and 1’s to 0. Suppose there is a binary number 11001001, then its one’s complement will be 00110110.
Now let us understand how this method is used to store numbers in the memory.
Let us suppose the number in binary format is 100111, which will be treated as a negative number since 1 is the leftmost bit. Now its one’s complement is 011000 which is 24 in the decimal format so we will treat 100111 as -24.
In this method, the problem which arose in the previous method is partially solved as addition now starts giving correct results but there is still some exceptions such as when we add 3 and -2 using this representation we get wrong output
3 -> 000011
-2-> 111101
After addition we get -> 000000 which is +0
Output was expected to be 1.
To further enhance this approach the numbers two complement format was introduced
Two’s complement of a number is similar to One’s complement with one extra step that after finding the one’s complement of the number 1 is added again to the result.
The two complements in the previous of 24(011000) will be 101000. This number when added with the original number 24 we get 000000 as output where the carry bit is ignored and the arithmetic operation passes.
24 -> 011000
two's complement of 24 -> 101000
Addition gives -> 1000000
// One is ignored as digits upto 6 bits are counted
So -24 will be stored as 101000 in the memory
Conclusion:
When storing Integers in unsigned bit simple binary format is followed
In order to store signed bit integers, the numbers internally will be stored as two’s complement so as to increase the storage capacity and improve arithmetic calculation.
Storing of Floating point numbers.
To store a float number we divide it into three parts sign bit, exponent, and mantissa.
- sign bit: It is used to indicate a sign of a number with convention as 0 for positive and 1 for negative.
- exponent: It is the difference between a real binary number and its normalized form.
- mantissa: It is used to store the fraction part of the floating point number’s normalized form.
Floating point numbers represented using 32-bit format are called single precision whereas the numbers represented using 64-bit format are called double precision
Storage Space required for storing number in different formats:
| |
sign |
exponent |
mantissa |
| single |
1 bit |
8 bits |
23 bits |
| double |
1 bit |
11 bits |
52 bits |
The concept of bias is used in the floating point representation to represent negative numbers too instead of one’s and two’s complement. Bias is used because comparison becomes difficult in the case of floating point numbers with two’s complement representations.
For eg., a normal 6-bit representation will follow numbers from 000000 to 111111 but IEEE has given a formula that will store the negative numbers too. If n is the number of bits the formula will be.
bias = 2(n-1) - 1
// Here n = 6
therefore bias = 31
This means in 6-bit representation we can store numbers from -31 to 32
Let us see how the binary number 101.101 will be represented in scientific notation.
we will get 1.01101 * 2^2
- Here, the sign bit is 0 and will be the leftmost bit
- The exponent is 2. It will indicate the distance between the original binary number and the normalized form.
- The mantissa is the fraction part which will be 01101
Storing of Irrational Numbers.
Computers are still incapable to store and manipulate irrational numbers so they cannot be stored.
How Numbers are stored internally in JavaScript:
Now let us understand how JavaScript internally manages to store the numbers. JavaScript does not have a separate format for Integer and Float representation. It uses Numbers for all types of numbers. Inside JavaScript, every number is stored as 64 floating-point numbers. In some cases for the arithmetic operation of integers, two’s complement format is used.
Problems with Floating Point Numbers in JavaScript
- The floating point numbers are not always accurate and give approximate results.
Example: In this example, we will try to understand the above problem.
Javascript
let x = 0.1;
let y = 0.2;
console.log(x+y);
|
Output: Here, instead of real calculation an approximate result is given for fast performance
0.30000000000000004
- Floating numbers give different output depending on their associativity
Example: We will understand the associativity problem with the example given below.
Javascript
let x = 0.1;
let y = 0.2;
let z = 0.3
console.log((x+y)+z);
console.log(x+(y+z));
|
Output: Since floating point calculations are based on rounding, therefore, the result is not always the same even though it should be the same in real-world applications.
0.6000000000000001
0.6
Become an expert in solving problems with DSA JavaScript—the course designed to teach you Data Structures and Algorithms using JavaScript. Over the next 90 days, dive deep into key DSA concepts, learn to optimize your code, and gain hands-on experience solving challenging problems. Whether you're a beginner or looking to refine your JavaScript skills, this course will provide the knowledge you need to succeed.
Take on the Three 90 Challenge today! Complete 90% of the course within 90 days, and you’ll earn a 90% refund. This challenge is your chance to stay motivated, improve your skills, and get rewarded for your progress. Don’t wait—start your journey to DSA mastery with JavaScript today!
Similar Reads
How numbers are stored in JavaScript ?
In this article, we will try to understand how numbers are stored in JavaScript. Like any other programming language, all the data is stored inside the computer in the form of binary numbers 0 and 1. Since computers can only understand and process data in the form of 0's and 1's. In JavaScript, ther
6 min read
How to create a Number object using JavaScript ?
In this article, we will discuss how to create a Number object using JavaScript. A number object is used to represent integers, decimal or float point numbers, and many more. The primitive wrapper object Number is used to represent and handle numbers. examples: 20, 0.25. We generally don't need to w
2 min read
How to convert a value to a safe integer using JavaScript ?
In this article, we will learn How to convert a value to a safe integer using JavaScript. We have given a number, and we have to convert it into a safe integer using JavaScript. Safe Integers are integers between -(253 - 1) and (253 - 1). Approach: First, we take input using the prompt in JavaScript
2 min read
How to add float numbers using JavaScript ?
Given two or more numbers the task is to get the float addition in the desired format with the help of JavaScript. There are two methods to solve this problem which are discussed below: Table of Content Using parseFloat() and toFixed() method Using parseFloat() and Math.round() method Using Number()
2 min read
Calculate current week number in JavaScript
Calculating the current week number involves determining which week of the year the current date falls into. The method of calculation can vary slightly depending on the rules you follow, such as which day starts the week (Sunday or Monday) and how the first week of the year is defined. For example:
2 min read
How to Convert a Float Number to the Whole Number in JavaScript?
Given a float number and the task is to convert a float number to a whole number using JavaScript. Below are various methods to convert float numbers to whole numbers in JavaScript: Table of Content Math.floor (floating argument)Math.ceil (floating argument) Math.round (floating argument)Math.trunc
4 min read
How to convert Number to Boolean in JavaScript ?
We convert a Number to Boolean by using the JavaScript Boolean() method and double NOT operator(!!). A JavaScript boolean results in one of two values i.e. true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e. "false" or "true". Below are
2 min read
Convert a Number to a String in JavaScript
These are the following ways to Convert a number to a string in JavaScript: 1. Using toString() Method (Efficient and Simple Method)This method belongs to the Number.Prototype object. It takes an integer or a floating-point number and converts it into a string type. [GFGTABS] JavaScript let a = 20;
1 min read
Convert a negative number to positive in JavaScript
In this article, we will see how we can convert a negative number to a positive number in JavaScript by the methods described below. Below are the methods to convert a negative number to a positive in JavaScript: Table of Content Multiplying by -1Using Math.abs()adding a minus signFlipping the bitUs
4 min read
Check a Number is Prime or Not Using JavaScript
Here are the different ways to check whether a number is Prime or not. 1. Iterative Check: Basic ApproachThis is the simplest way to check for prime numbers by iterating through all numbers from 2 to n-1 and checking divisibility. [GFGTABS] JavaScript let n = 17; let isPrime = true; if (n <= 1) {
4 min read
JavaScript - Convert a Number into JS Array
You have a number, like 12345, and you need to convert it into an array where each element represents a digit of the number. For example, 12345 should become [1, 2, 3, 4, 5]. How can you achieve this in JavaScript? In JavaScript, there are various ways to transform a number into an array of its digi
3 min read
How to generate a n-digit number using JavaScript?
The task is to generate an n-Digit random number with the help of JavaScript. You can also generate random numbers in the given range using JavaScript. Below are the approaches to generate a n-digit number using JavaScript: Table of Content Using Math.random()Math.random() Method and .substring() Me
2 min read
How to get decimal portion of a number using JavaScript ?
Given a float number, The task is to separate the number into integer and decimal parts using JavaScript. For example, a value of 15.6 would be split into two numbers, i.e. 15 and 0.6 Here are a few methods discussed. These are the following methods: Table of Content Javascript String split() Method
3 min read
Generate Random Number in Given Range Using JavaScript
Here are the different ways to generate random numbers in a given range using JavaScript 1. Using Math.random(): basic ApproachThis is the simplest way to generate a random number within a range using Math.random(). [GFGTABS] JavaScript let min = 10; let max = 20; let random = Math.floor(Math.random
3 min read
How to convert long number into abbreviated string in JavaScript ?
We are given a long number and the task is to convert it to the abbreviated string(eg.. 1234 to 1.2k). Here 2 approaches are discussed with the help of JavaScript. Approaches to Convert Long Number to Abbreviated String:Table of Content Using JavaScript methodsUsing Custom functionUsing logarithmsUs
6 min read
How to check first number is divisible by second one in JavaScript ?
Given two numbers and the task is to check the first number is divisible by the second number or not with the help of JavaScript. Before getting into the coding part, first let us know about the modulo operator and triple equals. To find a number is divisible by another or not, we simply use the rem
2 min read
JavaScript - How to Get a Number of Vowels in a String?
Here are the various methods to get the number of vowels in a string using JavaScript. 1. Using a for LoopThis is the most basic and beginner-friendly approach. It uses a loop to iterate over each character and checks if it is a vowel. [GFGTABS] JavaScript const cVowels = (s) => { const vowels =
3 min read
How to limit a number between a min/max value in JavaScript ?
We can limit a number between a min/max value using the is-else condition and using the Math.min and Math.max methods of JavaScript. Below are the approaches to limit a number between a min/max value in JavaScript: Table of Content Using the if-else conditionUsing the Math.min() and Math.max() metho
2 min read
How to convert a pixel value to a number value using JavaScript ?
In this article, we will see how to convert the string value containing 'px' to the Integer Value with the help of JavaScript. There are two approaches to converting a pixel value to a number value, these are: Using parseInt() MethodUsing RegExpApproach 1: Using parseInt() Method This method takes a
2 min read
How to count number of data types in an array in JavaScript ?
Given an array and the task is to count the number of data types used to create that array in JavaScript. Example: Input: [1, true, "hello", [], {}, undefined, function(){}] Output: { boolean: 1, function: 1, number: 1, object: 2, string: 1, undefined: 1 } Input: [function(){}, new Object(), [], {},
2 min read
How to print a number with commas as thousands separators in JavaScript?
Method 1: Using Intl.NumberFormat() The Intl.NumberFormat() object is used to represent numbers in language-sensitive formatting. It can be used to represent currency or percentages according to the locale specified.The locales parameter of this object is used to specify the format of the number. Th
2 min read
How to Calculate the Number of Days between Two Dates in JavaScript?
Given two Dates and the task is to get the number of days between two dates in JavaScript. To calculate the number of days between two dates in JavaScript, we use the Date object and subtract dates using milliseconds. Below are the methods commonly used to determine the number of days between two da
4 min read
How to check whether a number is NaN or finite in JavaScript ?
When working with numbers in JavaScript, it's important to know how to determine if a value is NaN (Not-a-Number) or finite. This knowledge is crucial for data validation, error handling, and ensuring your code behaves as expected. In this article, we will see how to check whether the number is NaN
3 min read
How to write a cell phone number in an international way using JavaScript ?
E.164 format is used to convert a phone number into an international format. It is an internationally recognized standard that defines a general numbering plan. The international number format according to E.164 is as follows: [+][country code][area code][local phone number] +: Plus sign country cod
3 min read
How to check a number is even without using modulo operator in JavaScript ?
In this article, we learn how to check if a number is even without using the % or modulo operator. The methods are mentioned below. 1. By using the bitwise '&' operator: When & operation is done on a number with 1 it will return 0 if the number is zero. We will use this method to check if th
3 min read