The Wayback Machine - https://web.archive.org/web/20240822172641/https://www.geeksforgeeks.org/javascript-calculator/
Open In App

JavaScript Calculator

Last Updated : 29 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript Calculator performs mathematical operations like – Addition, Subtraction, Multiplication, Division, etc.

HTML, CSS, and JavaScript are used to design the JavaScript Calculator. HTML creates basic structure of the calculator. CSS properties applies styles on the calculator and JavaScript adds the calculation functionality. Also, Math.js evaluates the calculations.

 

Approach to Create JavaScript Calculator

  • HTML Table creates a grid structure and <input type=”button”> adds the buttons on the grid.
  • <input type=”text”> adds an input text field to display the expression.
  • When the user clicks on the button, the button value will display on the input field.
  • When the equal button ( = ) is clicked, solve() function is called and evaluates the expression, and displays the result on the input text field.
  • The button “c” is used to clear the text input field. When the button is clicked, the clr() function is called, and it resets the value to empty.
  • The solve() function uses Math.js evaluate() function to evaluate the mathematical expression.

Complete Code

HTML




<!DOCTYPE html>
<html>
  
<head>
      <title>JavaScript Calculator</title>
    <script src=
        integrity=
"sha512-BbVEDjbqdN3Eow8+empLMrJlxXRj5nEitiCAK5A1pUr66+jLVejo3PmjIaucRnjlB0P9R3rBUs3g5jXc8ti+fQ=="
        crossorigin="anonymous"
        referrerpolicy="no-referrer"></script>
    <script src=
        integrity=
"sha512-iphNRh6dPbeuPGIrQbCdbBF/qcqadKWLa35YPVfMZMHBSI6PLJh1om2xCTWhpVpmUyb4IvVS9iYnnYMkleVXLA=="
        crossorigin="anonymous"
        referrerpolicy="no-referrer"></script>
    
    <!-- For styling -->
    <style>
        table {
            border: 1px solid black;
            margin-left: auto;
            margin-right: auto;
        }
  
        input[type="button"] {
            width: 100%;
            padding: 20px 40px;
            background-color: green;
            color: white;
            font-size: 24px;
            font-weight: bold;
            border: none;
            border-radius: 5px;
        }
  
        input[type="text"] {
            padding: 20px 30px;
            font-size: 24px;
            font-weight: bold;
            border: none;
            border-radius: 5px;
            border: 2px solid black;
        }
    </style>
</head>
    
<body>
    
      <!-- Use Table to Create Calculator Structure Design -->
    <table id="calcu">
        <tr>
            <td colspan="3"><input type="text" id="result"></td>
            <td><input type="button" value="c" onclick="clr()" /> </td>
        </tr>
        <tr>
            <td><input type="button" value="1" onclick="dis('1')"
                        onkeydown="myFunction(event)"> </td>
            <td><input type="button" value="2" onclick="dis('2')"
                        onkeydown="myFunction(event)"> </td>
            <td><input type="button" value="3" onclick="dis('3')"
                        onkeydown="myFunction(event)"> </td>
            <td><input type="button" value="/" onclick="dis('/')"
                        onkeydown="myFunction(event)"> </td>
        </tr>
        <tr>
            <td><input type="button" value="4" onclick="dis('4')"
                        onkeydown="myFunction(event)"> </td>
            <td><input type="button" value="5" onclick="dis('5')"
                        onkeydown="myFunction(event)"> </td>
            <td><input type="button" value="6" onclick="dis('6')"
                        onkeydown="myFunction(event)"> </td>
            <td><input type="button" value="*" onclick="dis('*')"
                        onkeydown="myFunction(event)"> </td>
        </tr>
        <tr>
            <td><input type="button" value="7" onclick="dis('7')"
                        onkeydown="myFunction(event)"> </td>
            <td><input type="button" value="8" onclick="dis('8')"
                        onkeydown="myFunction(event)"> </td>
            <td><input type="button" value="9" onclick="dis('9')"
                        onkeydown="myFunction(event)"> </td>
            <td><input type="button" value="-" onclick="dis('-')"
                        onkeydown="myFunction(event)"> </td>
        </tr>
        <tr>
            <td><input type="button" value="0" onclick="dis('0')"
                        onkeydown="myFunction(event)"> </td>
            <td><input type="button" value="." onclick="dis('.')"
                        onkeydown="myFunction(event)"> </td>
            
            <!-- solve function call function solve to evaluate value -->
            <td><input type="button" value="=" onclick="solve()"> </td>
  
            <td><input type="button" value="+" onclick="dis('+')"
                        onkeydown="myFunction(event)"> </td>
        </tr>
    </table>
  
    <script>
        
        // Function that display value
        function dis(val) {
            document.getElementById("result").value += val
        }
  
        function myFunction(event) {
            if (event.key == '0' || event.key == '1'
                || event.key == '2' || event.key == '3'
                || event.key == '4' || event.key == '5'
                || event.key == '6' || event.key == '7'
                || event.key == '8' || event.key == '9'
                || event.key == '+' || event.key == '-'
                || event.key == '*' || event.key == '/')
                document.getElementById("result").value += event.key;
        }
  
        var cal = document.getElementById("calcu");
        cal.onkeyup = function (event) {
            if (event.keyCode === 13) {
                console.log("Enter");
                let x = document.getElementById("result").value
                console.log(x);
                solve();
            }
        }
  
        // Function that evaluates the digit and return result
        function solve() {
            let x = document.getElementById("result").value
            let y = math.evaluate(x)
            document.getElementById("result").value = y
        }
  
        // Function that clear the display
        function clr() {
            document.getElementById("result").value = ""
        }
    </script>
</body>
  
</html>


Output:

JavaScript Calculator

JS Calculator



Previous Article
Next Article

Similar Reads

Design a Calculator using JavaScript with Neumorphism Effect/Soft UI
In this article, we will learn how to create a working calculator with the Neumorphism effect using HTML, CSS, and JavaScript. Basic mathematical operations such as addition, subtraction, multiplication, and division can be performed using this calculator. Approach: Neumorphism is a contemporary approach to decorating web-elements and creating a 3D
3 min read
How to Create a Binary Calculator using HTML, CSS and JavaScript ?
HTML or HyperText Markup Language along with CSS (Cascading Stylesheet) and JavaScript can be used to develop interactive user applications that can perform certain functionalities. Similarly, a binary calculator can be developed using HTML, CSS, and JS altogether. Binary Calculator performs arithmetic operations on binary numbers. Binary Calculato
5 min read
JavaScript Program for Chi-Square Critical Value Calculator
In this article, we will discuss the Chi-Square Critical Value Calculator. The Chi-Square Critical Value Calculator is a JavaScript tool used to determine critical values from the chi-square distribution. Chi-Square critical values help you decide if your study results are strong enough to conclude that there's a real difference or if it might just
2 min read
JavaScript Program for Kruskal-Wallis Test Calculator
In this article, we are going to implement the Kruskal-Wallis Test Calculator in JavaScript.It is designed to help researchers and analysts compare multiple groups of data and determine if there are significant differences in medians. This calculator can be particularly useful when the data doesn't meet the assumptions of the parametric tests or wh
3 min read
JavaScript Program for Bartlett's Test Calculator
In this article, we are going to implement Bartlett's test calculator in JavaScript. Bartlett's test is a statistical test used to determine whether the variances of multiple groups are homogeneous and plays a crucial role in various fields of experimental research such as analysis of variance and hypothesis testing. We built Bartlett's test calcul
3 min read
JavaScript Program for Inverse t Distribution Calculator
In this article, we will discuss the Inverse t Distribution Calculator using JavaScript. An inverse t-distribution calculator is a valuable tool for calculating critical values from the t-distribution. It helps researchers and analysts in hypothesis testing, confidence interval estimation, and other statistical calculations. Using jStat libraryIn t
2 min read
JavaScript Program for Normal CDF Calculator
In this article, we will discuss a normal CDF calculator in JavaScript. A CDF calculator computes the Cumulative Distribution Function (CDF) for a given statistical variable. It indicates the probability that the variable's value is less than or equal to a specified point, calculating the CDF is essential for understanding the probabilities associa
3 min read
Design a Tip Calculator using HTML, CSS and JavaScript
The tip is the money given as a gift for good service, to the person who serves you in a restaurant. In this project, a simple tip calculator is made which takes the billing amount, type of service, and the number of persons as input. As per the three inputs, it generates a tip for the serving person. In this article, we are going to learn how to d
4 min read
Design a Loan Calculator using JavaScript
The Loan Calculator can be used to calculate the monthly EMI of the loan by taking the total amount, months to repay, and the rate of interest. Formula Used:interest = (amount * (rate * 0.01))/months;total = ((amount/months) + interest);ApproachExtract values from HTML input elements (#amount, #rate, #months).Calculate monthly interest using the fo
2 min read
Create a Simple Interest Calculator using HTML CSS and JavaScript
Simple Interest is the term used to describe the rate at which money is borrowed or lent. Simple Interest Calculator serves as a practical tool for computing interest on loans or savings without compounding. It allows you to determine the simple interest on the principal amount, offering flexibility in calculating daily, monthly, or yearly interest
3 min read
BMI Calculator Card using Tailwind CSS & JavaScript
The Body Mass Index (BMI) Calculator can be used to calculate BMI values based on height and weight. BMI is a fairly reliable indicator of body fatness for most people. In this article, we will implement a BMI (Body Mass Index) Calculator using JavaScript with Tailwind CSS framework. Formula to calcuate BMI:BMI = (weight) / (height * height) height
3 min read
EMI Calculator Card using Tailwind CSS and JavaScript
An EMI (Equated Monthly Installment) calculator helps users determine the monthly payment amount towards a loan including both the principal amount and the interest. This project will demonstrate how to create a simple yet effective financial tool using the Tailwind CSS framework. Approach to create EMI Calculator CardFirstly, integrate the Tailwin
3 min read
Tip Calculator Card using Tailwind CSS & JavaScript
Tip Calculator in Tailwind CSS is a simple and user-friendly tool designed to help users calculate tips for various services. It allows users to input the total bill amount, select a tip percentage, and choose the number of people splitting the bill. The calculator then displays the tip amount, the total bill including the tip, and the amount each
3 min read
Design a Time Duration Calculator Card in Tailwind CSS & JavaScript
In this article, we'll create a simple Time Duration Calculator application using the Tailwind CSS and JavaScript. The application allows users to add a starting date &amp; time and an ending date &amp; time. And user gets the difference between these two dates as a output. We'll utilize Tailwind CSS for styling to create an attractive user interfa
3 min read
RC Time Constant Calculator Card using Tailwind CSS & JavaScript
The RC Time Constant Calculator is a web application designed to calculate the time constant (τ) of a resistor-capacitor (RC) circuit. It allows users to input the resistance and capacitance values of the circuit and then calculate the time constant based on these inputs. The calculator is designed with a clean and intuitive interface using the Tai
3 min read
LCM & GCD Calculator Card using Tailwind CSS & JavaScript
The LCM and GCD Calculator is a web application that allows users to calculate the Least Common Multiple (LCM) and Greatest Common Divisor (GCD) of the two numbers. Users input two numbers and the application computes and displays their LCM and GCD. Approach to create LCM &amp; GCD Calculator CardCreate the basic structure of the web page using HTM
3 min read
Current Ratio Calculator Card using Tailwind CSS & JavaScript
A Current Ratio Calculator is a web-based tool that allows users to calculate the current ratio of a company. The current ratio is a financial metric that measures a company's ability to pay its short-term liabilities with its short-term assets. It is calculated by dividing the company's current assets by its current liabilities. The calculator is
3 min read
Factorial Calculator Card using Tailwind CSS and JavaScript
The Factorial Calculator is a web application designed to calculate the factorial of a non-negative integer entered by the user and instantly compute its factorial upon a button click. If the user wants to start over, they can utilize the "Clear" button. Its design and user-friendly features ensure a smooth user experience. Approach to create Facto
2 min read
How to create NPV Calculator Card using JavaScript & Tailwind CSS ?
A Net Present Value (NPV) Calculator is a web-based tool that helps users calculate the net present value of an investment. It typically includes input fields for the initial investment amount, the discount rate, and the expected cash flows. The calculator then calculates the NPV based on these inputs. The calculator is styled using Tailwind CSS, a
3 min read
How to create Dividend Payout Ratio Calculator Card using JavaScript & Tailwind CSS ?
A Dividend Payout Ratio Calculator is a web-based tool that helps users calculate the percentage of a company's earnings that are paid out as dividends to shareholders. The dividend payout ratio is a financial metric that measures the proportion of earnings that are distributed to shareholders as dividends. It is calculated by dividing the total di
3 min read
How to create Calculator Card using Tailwind CSS & JavaScript ?
In this article, we'll create a Basic Calculator using the Tailwind CSS and JavaScript. The application allows users to input any numerical data and give the calculated result. We'll utilize Tailwind CSS for styling to create an attractive user interface and JavaScript for the logic. Approach to create Calculator Card in Tailwind &amp; JavaScriptCr
3 min read
How to create GPA Calculator Card using JavaScript and Tailwind CSS ?
A GPA (Grade Point Average) Calculator using Tailwind CSS, and JavaScript allows users to input the credits and select the grade for each course, and it will calculate the GPA based on these inputs. Output Preview: Let us have a look at how the final output will look like. Approach to create GPA Calculator Card:Create the basic structure of the web
4 min read
Create Aspect Ratio Calculator using HTML CSS and JavaScript
In this article, we are going to implement an aspect ratio calculator. An aspect ratio calculator proves to be a useful tool for individuals seeking to determine the proportions of images or videos based on their width and height. Our aspect ratio calculator has a live preview option that enables users to visualize how adjustments in width and heig
5 min read
CGPA Calculator using HTML CSS & JavaScript
Nowadays, colleges use grades like A, B, C, D, and F, and assign credits to courses. In this calculator, you just need to input your subject name, grade, and credit. We'll also include options to update or delete information in case of mistakes. This way, you won't have to re-enter all details if you make an error. Let's begin creating the CGPA cal
4 min read
Geometry Calculator Design using HTML CSS and JavaScript
In this article, we will see how to design a Geometry Calculator using HTML, CSS, and JavaScript. A Geometry calculator is used to calculate the area and parameters of different shapes and figures, like circles, rectangles, squares, triangles, etc. This can be helpful in cases where one wants to calculate the circumference or the area covered by an
4 min read
Age Calculator Design using HTML CSS and JavaScript
In Age Calculator, we will take the date of birth as the date input and it prints the age from the current date (or specified date). We will create the structure of the Age Calculator using HTML and CSS, and JavaScript will add the functionality to calculate the age in years, months, and days. ApproachCreate the Calculator structure using an HTML i
3 min read
Percentage calculator using HTML CSS and JavaScript
The percentage calculator is useful for students, shopkeepers, and for solving basic mathematical problems related to percentages. In this article, we are going to learn, how to make a percentage calculator using HTML CSS, and JavaScript Formula used:What is X percent of Y is given by the formula: X percent of Y =(X/100)* YX is what percent of Y is
4 min read
Create a Profit and Loss Calculator using JavaScript
In this article, we will create a profit &amp; loss calculator using HTML, CSS &amp; Javascript for adding the basic functionality along with adding the design and layout. Profit and Loss Calculator is basically used to calculate the amount or percentage received after selling a particular price or goods. If the amount(Selling Price) received is gr
3 min read
Design a Student Grade Calculator using JavaScript
A Student Grade Calculator is a tool used to compute students' grades based on their scores in various assessments, such as assignments, quizzes, exams, or projects. It helps standardize grading, ensures accuracy, and provides students with a clear understanding of their academic performance. Formulapercentage = ( totalgrades / 400 ) * 100 ;Example
4 min read
Design a BMI Calculator using JavaScript
A BMI (Body Mass Index) Calculator measures body fat based on weight and height, providing a numerical value to categorize individuals as underweight, normal weight, overweight, or obese. It’s widely used to assess health risks and guide lifestyle or medical decisions. A BMI Calculator using JavaScript allows users to input their weight and height,
3 min read
three90RightbarBannerImg