How to Deal with Large Numbers in JavaScript ?
In this article, we will see the methods to deal with large numbers in Javascript.
Large numbers are the numbers that can hold huge memory and evaluation time is more than exceeds space and time to process.
We can deal with large numbers in JavaScript using the data type BigInt.
Advantages:
- It can hold numbers of large sizes.
- It performs arithmetic operations.
Disadvantages:
- Consumes huge memory.
Approach: By default, JavaScript converts a big number by adding e+39 at the end of it.
var variable_name = value This will print e+39 at last var bigi = 41234563232789012327892787227897329; Output: 4.123456323278901e+34
So in order to remove this, add ‘n’ at end of the number
var bigi = 41234563232789012327892787227897329n; output: 41234563232789012327892787227897329 They are used in numerical calculations used along with operands
Example 1: This example shows the use of the above-explained approach.
HTML
< h1 style = "text-align:center;color:green" > GeeksforGeeks </ h1 > < p id = "gfg1" ></ p > < p id = "gfg2" ></ p > < script > var bigit = 41234563232789012327892787227897329; document.getElementById("gfg1").innerHTML = "The value of bigit is: " + bigit; // Displaying full number var bigit1 = 41234563232789012327892787227897329n; document.getElementById("gfg2").innerHTML = "The value of bigit1 is: " + bigit1; </ script > |
Output:
Example 2: This example shows the use of the above-explained approach.
HTML
< h1 style = "text-align:center;color:green" > GeeksforGeeks </ h1 > < p id = "gfg2" ></ p > < p id = "gfg3" ></ p > < p id = "gfg4" ></ p > < p id = "gfg5" ></ p > < p id = "gfg6" ></ p > < p id = "gfg7" ></ p > < script > var bigit1 = 41234563232789012327892787227897329n; document.getElementById("gfg2").innerHTML = "The value of bigit1 is: " + bigit1; // The value of bigit1 is: // 41234563232789012327892787227897329 // The value of bigi is: // 71234563232789012327892787227897329 var bigi = 71234563232789012327892787227897329n; document.getElementById("gfg3").innerHTML = "The value of bigi is: " + bigi; // Addition var z = bigit1 + bigi document.getElementById("gfg4").innerHTML = "The Addition result is: " + z; // The Addition result is: // 112469126465578024655785574455794658 //subtraction var a = bigit1 - bigi document.getElementById("gfg5").innerHTML = "The subtraction result is: " + a; // The subtraction result is: // -30000000000000000000000000000000000 // Multiplication var b = bigit1 * bigi document.getElementById("gfg6").innerHTML = "The multiplication result is: " + b; // The multiplication result is: // 293732610198254581311205146182139547 // 9295010026777045763269038565334241 // Division var c = bigit1 / bigi document.getElementById("gfg7").innerHTML = "The division result is: " + c; // The division result is: 0 </ script > |
output:
Please Login to comment...