Calculator Program In Javascript

Calculator Program In Javascript | HTML, CSS, Switch, If Else

A JavaScript calculator program enables users to perform arithmetic operations on numerical values using a web browser. Users input information through buttons on the interface, and the program displays the output on the screen. The program is an excellent tool for students, professionals, and anyone who requires quick and easy access to calculations. Here is an example of a basic calculator program in Javascript:

<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calc(value) {
    document.getElementById("result").value += value;
}
function clearResult() {
    document.getElementById("result").value = "";
}
function calculate() {
    var expression = document.getElementById("result").value;
    var result = eval(expression);
    document.getElementById("result").value = result;
}
</script>
</head>
<body>
    <table>
        <tr>
            <td colspan="4"><input type="text" id="result"></td>
        </tr>
        <tr>
            <td><button onclick="calc('1')">1</button></td>
            <td><button onclick="calc('2')">2</button></td>
            <td><button onclick="calc('3')">3</button></td>
            <td><button onclick="calc('+')">+</button></td>
        </tr>
        <tr>
            <td><button onclick="calc('4')">4</button></td>
            <td><button onclick="calc('5')">5</button></td>
            <td><button onclick="calc('6')">6</button></td>
            <td><button onclick="calc('-')">-</button></td>
        </tr>
        <tr>
            <td><button onclick="calc('7')">7</button></td>
            <td><button onclick="calc('8')">8</button></td>
            <td><button onclick="calc('9')">9</button></td>
            <td><button onclick="calc('*')">*</button></td>
        </tr>
        <tr>
            <td><button onclick="calc('0')">0</button></td>
            <td><button onclick="calc('.')">.</button></td>
            <td><button onclick="clearResult()">C</button></td>
            <td><button onclick="calc('/')">/</button></td>
        </tr>
        <tr>
            <td colspan="4"><button onclick="calculate()">=</button></td>
        </tr>
    </table>
</body>
</html>

The program uses a simple HTML table to create the interface for the calculator. The buttons on the interface are linked to Javascript functions that perform the desired operations. The calc function is used to append the clicked button’s value to the result input field. The clearResult function clears the input field. The calculate function evaluates the expression entered in the input field and displays the result in the same field.

Javascript-calculator GitHub

JavaScript Calculator is an online calculator application developed using JavaScript and HTML/CSS. This is a popular project on GitHub, where developers can view, use, and contribute to the code. Developers can submit pull requests and study the source code for the JavaScript Calculator on GitHub. Using it is a great way to learn more about JavaScript and how to create a basic calculator application.

There is a well-documented code for the JavaScript Calculator on GitHub, which includes comments explaining its purpose and functionality. Developers can therefore easily understand the logic behind the calculator’s operations and modify the code accordingly.

JavaScript Calculation Functions

Certainly! Below are examples of basic calculation functions using JavaScript. These functions cover addition, subtraction, multiplication, division, square root, and power operations. You can use these functions in a web page or any JavaScript environment:

Basic Arithmetic Operations:

let sum = 5 + 3; // Addition
let difference = 8 - 3; // Subtraction
let product = 4 * 6; // Multiplication
let quotient = 12 / 4; // Division

Exponentiation: let result = Math.pow(2, 3); // 2 raised to the power of 3

Square Root: let squareRoot = Math.sqrt(25); // Square root of 25

Random Number: let randomNum = Math.random(); // Generates a random number between 0 (inclusive) and 1 (exclusive)

Round, Ceil, and Floor: let roundedNum = Math.round(4.6); // Rounds to the nearest integer
let ceilNum = Math.ceil(4.2); // Rounds up to the nearest integer
let floorNum = Math.floor(4.9); // Rounds down to the nearest integer

Absolute Value: let absoluteValue = Math.abs(-10); // Absolute value of -10

Trigonometric Functions (in radians): let sineValue = Math.sin(Math.PI / 2); // Sine of 90 degrees (π/2 radians) let cosineValue = Math.cos(Math.PI); // Cosine of 180 degrees (π radians)

Simple calculator program in JavaScript using function

A simple calculator program in JavaScript using function is a program that allows users to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. This program is based on the concept of functions, which are a set of statements that perform a specific task. Here is an example of a simple calculator program in JavaScript using function:

function add(num1, num2) {
  return num1 + num2;
}

function subtract(num1, num2) {
  return num1 - num2;
}

function multiply(num1, num2) {
  return num1 * num2;
}

function divide(num1, num2) {
  return num1 / num2;
}

var num1 = parseFloat(prompt("Enter first number: "));
var num2 = parseFloat(prompt("Enter second number: "));
var operation = prompt("Enter operation (add, subtract, multiply, divide): ");

var result;

if (operation == "add") {
  result = add(num1, num2);
} else if (operation == "subtract") {
  result = subtract(num1, num2);
} else if (operation == "multiply") {
  result = multiply(num1, num2);
} else if (operation == "divide") {
  result = divide(num1, num2);
} else {
  result = "Invalid operation!";
}

alert("Result: " + result);

In this program, four functions are defined for addition, subtraction, multiplication, and division. Each function takes two parameters as input (num1 and num2) and returns the result of the corresponding operation.

The program then prompts the user to enter two numbers and the operation to perform. The input numbers are converted to floats using the parseFloat() function to ensure accurate calculation.

The program then uses the if else statement to determine which function to call based on the user’s input for the operation. The result of the operation is then displayed using the alert() function.

Calculator in Javascript Using Function

Create a simple calculator in JavaScript using functions. We’ll show a basic calculator that can perform addition, subtraction, multiplication, and division operations. Here’s the code:

Simple Calculator





 

Calculator using JavaScript HTML and CSS

A Calculator using JavaScript, HTML, and CSS is a web-based calculator that can perform basic arithmetic operations. Here’s the code with step-by-step explanation.

  1. Create an HTML file and add the basic structure of a web page, including a title and a container div for the calculator.
  2. Inside the container div, create a form element with a class of “calculator-form” and an input element with a class of “calculator-screen”.
  3. Next, create a table element with a class of “calculator-keys”. Inside the table, create table rows and table data cells for each button on the calculator.
  4. Assign an ID to each button that corresponds to the value it should input into the calculator screen.
  5. Create a CSS file and add styles for the calculator, including the colors and layout of the buttons.
  6. Add a link to the CSS file in the head of the HTML document.
  7. Create a JavaScript file and link it to the HTML document.
  8. Add an event listener to the calculator-form element to listen for button clicks.
  9. Inside the event listener, use JavaScript to capture the value of the clicked button and update the calculator screen with the value.
  10. Use JavaScript to perform the necessary calculations when the user clicks the equals button.
  11. Update the calculator screen with the result of the calculation.
  12. Add error handling to the calculator so that it can handle invalid input and divide-by-zero errors.
  13. Test the calculator to ensure that it works as expected.
<!DOCTYPE html>
<html>
<head>
	<title>Calculator</title>
	<style>
		body {
			background-color: #f1f1f1;
			font-family: Arial, sans-serif;
		}
		
		#calculator {
			background-color: #fff;
			width: 300px;
			margin: auto;
			padding: 20px;
			border-radius: 10px;
			box-shadow: 2px 2px 10px #888;
		}
		
		#result {
			font-size: 36px;
			text-align: right;
			margin-bottom: 10px;
			padding: 10px;
			border: none;
			background-color: #eee;
			width: 100%;
			border-radius: 5px;
			box-shadow: 1px 1px 5px #888;
		}
		
		.button {
			background-color: #4CAF50;
			border: none;
			color: white;
			padding: 10px;
			text-align: center;
			text-decoration: none;
			display: inline-block;
			font-size: 20px;
			margin: 4px 2px;
			cursor: pointer;
			width: 70px;
			height: 70px;
			border-radius: 50%;
			box-shadow: 1px 1px 5px #888;
		}
		
		.button:hover {
			background-color: #3e8e41;
		}
	</style>
</head>
<body>
	<div id="calculator">
		<input type="text" id="result" readonly>
		<button class="button" onclick="clearResult()">C</button>
		<button class="button" onclick="addToResult('/')">/</button>
		<button class="button" onclick="addToResult('*')">*</button>
		<button class="button" onclick="addToResult('7')">7</button>
		<button class="button" onclick="addToResult('8')">8</button>
		<button class="button" onclick="addToResult('9')">9</button>
		<button class="button" onclick="addToResult('-')">-</button>
		<button class="button" onclick="addToResult('4')">4</button>
		<button class="button" onclick="addToResult('5')">5</button>
		<button class="button" onclick="addToResult('6')">6</button>
		<button class="button" onclick="addToResult('+')">+</button>
		<button class="button" onclick="addToResult('1')">1</button>
		<button class="button" onclick="addToResult('2')">2</button>
		<button class="button" onclick="addToResult('3')">3</button>
		<button class="button" onclick="calculate()">=</button>
		<button class="button" onclick="addToResult('0')">0</button>
		<button class="button" onclick="addToResult('.')">.</button>
	</div>
	
	<script>
		function addToResult(value) {
			document.getElementById("result").value += value;
		}
		
		function clearResult() {
			document.getElementById("result").value = "";
		}
		
		function calculate() {
			var result = eval(document.getElementById("result").value);
			document.getElementById("result").value = result;
		}
	</script>
</body>
</html>

Calculator in JavaScript using switch case

A calculator in JavaScript using switch case is a program that allows users to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. It works by taking in two input values and an operator from the user, then performing the selected operation and displaying the result. Here is the code for a calculator in JavaScript using switch case:

function calculate(num1, num2, operator) {
  let result;
  switch (operator) {
    case "+":
      result = num1 + num2;
      break;
    case "-":
      result = num1 - num2;
      break;
    case "*":
      result = num1 * num2;
      break;
    case "/":
      result = num1 / num2;
      break;
    default:
      result = "Invalid operator";
  }
  return result;
}

// Example usage:
console.log(calculate(5, 10, "+")); // Output: 15
console.log(calculate(20, 5, "-")); // Output: 15
console.log(calculate(6, 3, "*")); // Output: 18
console.log(calculate(20, 4, "/")); // Output: 5
console.log(calculate(4, 5, "%")); // Output: "Invalid operator"

In this code, the calculate function takes in three parameters: num1, num2, and operator. The function then uses a switch statement to determine which operation to perform based on the value of operator. The result variable is set to the result of the operation, and then returned by the function.

The function can be used by passing in two numbers and an operator as arguments, and it will return the result of the calculation. If an invalid operator is passed in, the function will return the string “Invalid operator”.

Simple calculator in JavaScript using if else

A simple calculator program in JavaScript using if-else statements is a program that performs basic arithmetic operations such as addition, subtraction, multiplication, and division based on user input. Here’s the code for a simple calculator program in JavaScript using if-else:

let num1 = parseInt(prompt("Enter first number: "));
let num2 = parseInt(prompt("Enter second number: "));
let operator = prompt("Enter operator (+, -, *, /): ");

if (operator == "+") {
  console.log(num1 + num2);
} else if (operator == "-") {
  console.log(num1 - num2);
} else if (operator == "*") {
  console.log(num1 * num2);
} else if (operator == "/") {
  console.log(num1 / num2);
} else {
  console.log("Invalid operator");
}

Explanation:

  • The program prompts the user to enter two numbers and an operator.
  • The parseInt() function is used to convert the user input into integers.
  • The if-else statements check which operator was entered and perform the corresponding arithmetic operation using the +, -, *, and / operators.
  • If an invalid operator is entered, the program displays an error message using the console.log() function.

This simple calculator program using if-else statements can be further improved by adding error handling for division by zero or invalid input.

FAQs:

  1. Can I create a calculator with JavaScript?

    Yes, a calculator can be created using JavaScript including HTML and CSS web programming. In this Calculator, we can perform basic operations like addition, multiplication, subtraction, and division. In this article, we have explained the complete process of creating a calculator with JavaScript.

Note: All the above-mentioned dates are tentative, So kindly visit the official website for all the information. If you find any inaccuracies or improper content on the website, please e-mail help[@]universityadmission2023[dot]inThere is no guarantee that the information on this website is accurate. It is provided solely for informational purposes.

Leave a Reply

Your email address will not be published. Required fields are marked *