Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Percentage calculator using HTML CSS and JavaScript
Next article icon

How to Create a Binary Calculator using HTML, CSS and JavaScript ?

Last Updated : 05 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Calculator has a buffer limit of 8 bits. If the result of the arithmetic operation exceeds 8 bits then the extraneous bits are truncated. The arithmetic operations are accomplished using JavaScript functions. 

The application consists of a display screen where the user input as well as the result of the arithmetic operation is displayed. Two buttons 0 and 1 are used to take input. The + , - , * , / and Calculate buttons are used to perform an arithmetic operation on the input. 

The Calculate button is binded with a JavaScript function calculate(). When the Calculate button is clicked the calculate() function is triggered and the HTML within the 'output' division is parsed. The first number and second number are obtained by splitting the string and finally, they are converted into integers using parseInt(). The method parseInt() takes two arguments of which the first is the string to be converted to an integer and the second is the base value which is 2 or binary in this case. 

Arithmetic operations are performed depending on the addition, subtraction, multiplication, or division operator chosen by the user. The input() function receives the input from the user and displays it on the screen. The backspace() function deletes the last character of the string displayed. The cls() function clears the display screen. The following code snippets implement a binary calculator.

Example: When an input is given by the user, the input remains within the 'output' division in the form of HTML. A global variable scr is declared which can be accessed by all the JavaScript functions. When any input is given it is stored in the scr variable. When the Calculate button is clicked the string stored in the scr variable is searched for the presence of an operator using indexOf() method which returns the index of the operator if found else returns -1. If the operator is present the string stored in scr variable is split at the operator symbol (+,-,*,/), and the strings are stored in the num array. Since the input is in String format it must be converted to binary integer format to perform the calculations. The strings are parsed using parseint(str,base) method where str is the string to be converted and the base is the base of the number (here binary base = 2). After the binary conversion, the specified arithmetic operation is performed and the result is again stored in scr variable and displayed in the 'output' division.

html
<!DOCTYPE html> <html>     <head>         <meta charset="utf-8" />         <title>Binary Calculator</title>                <!--Bootstrap 4 CSS CDN -->         <link rel="stylesheet"                href= "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"                integrity= "sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"                crossorigin="anonymous" />     </head>      <body>         <div class="container">             <div class="jumbotron">                 <h1>Binary Calculator</h1>                 <div id="output"></div>                 <div class="container mt-2">                     <div class="row">                         <div class="col-12">                             <button type="button"                                      class="btn btn-light"                                      onclick="input('0')">                                       0</button>                             <button type="button"                                      class="btn btn-light"                                      onclick="input('1')">                                       1</button>                             <button type="button"                                      class="btn btn-danger float-right ml-2"                                      onclick="cls()">                                       AC</button>                             <button type="button"                                      class="btn btn-warning float-right"                                      onclick="backspace()">                                       Backspace</button>                         </div>                     </div>                     <div class="row mt-2">                         <div class="col-12">                             <button type="button"                                      class="btn btn-info"                                      onclick="input('+')">+</button>                             <button type="button"                                     class="btn btn-info"                                      onclick="input('-')">-</button>                             <button type="button"                                      class="btn btn-info"                                      onclick="input('*')">*</button>                             <button type="button"                                      class="btn btn-info"                                      onclick="input('/')">/</button>                         </div>                     </div>                     <div class="row mt-2">                         <div class="col-12">                             <button type="button"                                      class="btn btn-success"                                      onclick="calculate()">Calculate</button>                         </div>                     </div>                 </div>             </div>         </div>         <!--jquery and popper.js cdn -->         <script src= "https://code.jquery.com/jquery-3.5.1.slim.min.js"                  integrity= "sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"                  crossorigin="anonymous"></script>         <script src= "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"                  integrity= "sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"                  crossorigin="anonymous"></script>     </body> </html> 
CSS
.jumbotron {     width: 60%;     margin: auto;     text-align: center; }  #output {     border: 2px solid black;     min-height: 60px;     text-align: right;     font-weight: bold;     font-size: 20px; }  .btn {     min-width: 120px;     border: 2px solid black; } 
JavaScript
var scr = ""; //declared as global v function calculate() {     if (scr.indexOf("+") != -1) {         // If + is present in the string         // String obtained from scr is split         var num = scr.split("+");          // The splitted string stores in num array         var x = parseInt(num[0], 2);          // The num[0] and num[1] are the two binary          // numbers resp         var y = parseInt(num[1], 2);         var sum = x + y;         var ans = sum.toString(2);     } else if (scr.indexOf("-") != -1) {          // If - is present in the string         var num = scr.split("-");         var x = parseInt(num[0], 2);         var y = parseInt(num[1], 2);         var sub = x - y;         var ans = sub.toString(2);     } else if (scr.indexOf("*") != -1) {          // If * is present in the string         var num = scr.split("*");         var x = parseInt(num[0], 2);         var y = parseInt(num[1], 2);         var mul = x * y;         var ans = mul.toString(2);     } else if (scr.indexOf("/") != -1) {          // If / is present in the string         var num = scr.split("/");         var x = parseInt(num[0], 2);         var y = parseInt(num[1], 2);         var div = x / y;         var ans = div.toString(2);     }     scr = ans;     document.getElementById("output").innerHTML = scr;      function input(ch) {         scr += ch;         document.getElementById("output").innerHTML = scr;          function backspace() {             var b = document.getElementById("output").innerHTML;             scr = b.substring(0, b.length - 1);             document.getElementById("output").innerHTML = scr;              function cls() {                 scr = "";                 document.getElementById("output").innerHTML = scr;             } 

Output:


Next Article
Percentage calculator using HTML CSS and JavaScript

S

Shreyasi_Chakraborty
Improve
Article Tags :
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • Technical Scripter 2020
  • JavaScript-Questions
  • JavaScript-Projects

Similar Reads

    HTML Calculator
    HTML calculator is used for performing basic mathematical operations like Addition, subtraction, multiplication, and division.You can find the live preview below, try it: To design the basic calculator, we will use HTML , CSS , and JavaScript . HTML is used to design the basic structure of the calcu
    3 min read
    JavaScript Calculator
    To build a simple calculator using JavaScript, we need to handle basic arithmetic operations such as addition, subtraction, multiplication, and division. JavaScript, along with HTML and CSS, is commonly used to create interactive web-based calculators.What We Are Going to CreateWe will build a simpl
    7 min read
    JavaScript Scientific Calculator
    The HTML Scientific Calculator is a tool for performing advanced scientific calculations like finding exponents, logarithms, factorials, and more. This calculator comprises two sections: the input section, where the user types in their mathematical problem, and the output screen, which displays all
    4 min read
    JavaScript Neumorphism Effect Calculator
    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 app
    3 min read
    JavaScript Age Calculator
    In the Age Calculator, the user enters their date of birth using a date input field. The tool calculates and displays the exact age in years, months, and days from the current date (or a specified date). We'll design the layout using HTML and CSS, and add functionality using JavaScript. It will also
    3 min read
    JavaScript Tip Calculator
    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 that 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.
    4 min read
    JavaScript Geometry Calculator
    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 cal
    4 min read
    JavaScript Aspect Ratio Calculator
    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 us
    5 min read
    JavaScript Binary Calculator
    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 arithme
    5 min read
    JavaScript Percentage Calculator
    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 JavaScriptFormula used:What is X percent of Y is given by the formula: X
    3 min read
    JavaScript Profit and Loss Calculator
    In this article, we will create a profit & loss calculator using HTML, CSS & 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
    3 min read
    JavaScript BMI Calculator
    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 JavaScri
    3 min read
    JavaScript Temperature Calculator
    In this article, we will see Temperature Conversion between Celsius, Fahrenheit & Kelvin using HTML CSS & JavaScript. The Temperature is generally measured in terms of unit degree., i.e. in degrees centigrade, in degrees, Fahrenheit & Kelvin. Celsius is a standard unit of temperature on
    3 min read
    JavaScript Student Grade Calculator
    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.Formula
    4 min read
    JavaScript Loan Calculator
    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,
    2 min read
    JavaScript Interest Calculator
    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
    3 min read
    JavaScript CGPA Calculator
    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 yo
    4 min read
    JavaScript Bartletts 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 h
    3 min read
    JavaScript Unit Converter
    In this article, we will be developing an interactive and styled unit converter using HTML, CSS, and JavaScript.In this application, we have a select category option box in which different types of units are specified, like temperature, area, weight, length, and time. As per the user selection, the
    7 min read
    JavaScript Length Converter
    In this article, we will learn how to create a length converter using HTML, CSS, and JavaScript. The Length Converter is an intuitive web-based application that eliminates the complexities associated with manual conversions. Its user-friendly interface allows users to input a numerical value and sel
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences