JavaScript calculator

JavaScript calculator

In this article, we create a simple calculator with JavaScript, to further explain the getElementById () method.

This is also a simple exercise proposed for educational purposes, later we will develop the same exercise using jQuery.

JavaScript calculator – development

The simple calculator example we’re going to make today uses HTML, CSS, and even JavaScript.

Here is the example.

Enter the numbers and operations by clicking on the buttons and finally click on the equal button (=) to get the result of the operation. Now you can continue to operate on the number obtained or, if you want to delete all the contents of the display, click on the C button.

First we create the HTML code to insert the keys from 0 to 9, then we insert the buttons for the mathematical operations, the key for the comma, the C key and finally the equal key. We also insert the display at the top.

We will then use the div tags, the input tags and the button tag, to which we will assign appropriate classes, to format our calculator with JavaScript, as shown in the example above.


 

We also note that, at the onclick event for the keys, we entered n (this.id), in this way we automatically retrieve the id that is declared in each input. While the onclick event of button we assign the function operation () that we will create in JavaScript.

We then create the style sheet.


.content {
            margin-left: 2px;
        }
.key{
            background-color: #a5cff3 ;
            color: #175c97;
            font-size: 22pt;
            border: none;
            margin: 4px 2px;
            height: 40px;
	    width: 46px;
        }
.display {
            background: none;
            color: #175c97;
            font-size: 24pt;
            border: #175c97 solid 2px;
            margin: 4px 2px;
            width: 204px;
            height: 40px;            
        }
.egual{
            width: 208px;
        }

Of course, you can customize your calculator with JavaScript with the desired formatting.

Finally we implement the JavaScript code.

The code is really very simple. We create the function n (data) which from time to time takes the data entered by clicking on the keys as it uses the getElementById () method.

Then we create the function that performs the operations using the eval statement which will return the result of our operation.

Finally we realize the function that simply clears the display.


function n(ops){ 
   document.getElementById("operations").value += ops;
}

function op() { 
   document.getElementById("operations").value = eval(document.getElementById("operations").value); 
}

function reset_all() { 
   document.getElementById("operations").value = ""; 
}

As I told you this is a simple method to create a calculator with JavaScript, you can find many other solutions.

Alcuni link utili

Tutorial JavaScript

Decimal to Binary conversion

Decimal to Binary conversion

In this lesson we will learn how to make a decimal to binary conversion in JavaScript.

Try the converter below, write the number and then the conversion will automatically appear in the various systems.

Binary:

Octal:

Hexadecimal:

Furthermore, we will convert the decimal number into binary, octal and hexadecimal.

Decimal to Binary conversion online

Let’s proceed with the implementation of the various functions necessary to carry out the conversion.

First of all we develop the dec_bin function which deals with converting from decimal to binary, considering the remainder of division by 2. The function returns the binary number thus converted.

Then we develop the dec_ott function which deals with converting from decimal to octal, considering the remainder of division by 8. The function returns the octal number thus converted.

Then we implement the dec_esa function which takes care of converting from decimal to hexadecimal, considering the remainder of division by 16. If the remainder is greater than 9, the corresponding letter is taken from the array. The function then returns the converted hexadecimal number.

Finally we insert the change function which activates the automatic change when we insert the value in the decimal field.

So here is the complete JavaScript code for the binary decimal converter:



function dec_bin(num){
	binary = "";

	while(num!=0) {
		r = num % 2; 
		num = (num-r)/2; 
		binary = r + binary;
	}
	
	return binary;
}


function dec_ott(num){ 
	octal = "";

	while(num!=0) {
		r = num % 8; 
		num = (num - r)/8;
		octal = r + octal;
	}
	
	return octal;
}

function dec_esa(num){
	exa = ""; 
	while(num != 0) { 
		r = num % 16; 
		num = (num - r)/16; 
		ar = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
		if (r > 9) 
			r = ar[r]; 
		exa = r + exa ;
	}
	
	return exa ;
}


function change(name) {
		n = document.getElementById("decimale").value;
                result = dec_bin(n);
		result2 = dec_ott(n);
		result3 = dec_esa(n);
		risultato.value=result;
		risultato2.value=result2;
		risultato3.value=result3;
}

In the field, where I insert the decimal number as input, I add the onkeyup event. This causes the other fields to update automatically by calling the change function developed in JavaScript.


 

Clearly this is just a simple way to implement a binary decimal converter, which also allows you to convert to octal and hexadecimal. Feel free to propose your solution in the comments below.

Alcuni link utili

Indice argomenti tutorial JavaScript

Template responsive con html

Come creare un css responsive

Come trovare immagini per il sito web

Quali colori scegliere per un sito web

Quali font scegliere per un sito web

PDF da un form con JavaScript

Binary to decimal conversion

Binary to decimal conversion

In this lesson we will learn how to make a binary to decimal conversion in JavaScript.

Try the converter below, write the number and then the conversion will automatically appear in the various systems.

Decimale:

Binary to decimal conversion in JavaScript

First of all, let’s set up the HTML part of the code.

In our case it will simply be two input boxes:


 

I have inserted on the input box two events:

  • onkeyup which uses for the change function;
  • onkeypress which it uses to check if the number is valid.

Of course I could also handle these events in a different way on the JavaScript side.

We then develop the isValidNumber function, which verifies that the input number is 0 or 1. In this way, if we try to type other numbers or letters they will not be taken into consideration.


        function isValidNumber(e) {

            if (e.keyCode == 48 || e.keyCode == 49) {
                return true;
            }

            return false;
        }

Let’s now develop a function that allows you to transform the binary number under consideration into a decimal.

We follow this method:

  • We transform the number entered in the input field with binary id into a list;
  • Let’s invert the list;
  • We apply the forEach method to scroll through the list.
    • Dunquem, for each element we check that the number is 1. If the condition is satisfied, the reference power is added to the decimal variable, obtained thanks to the use of index.
  • The decimal number obtained is returned.

Here is therefore a possible implementation of the algorithm for binary decimal conversion in JavaScript:


        function bin_dec(num){
           decimal = 0;

            num = Array.from(String(num), Number);
            num = num.reverse();

            num.forEach((number, index) => {

                    if (number == 1) {
                        decimal += Math.pow(2, index);
                    }

                })  

            return decimal;
        }

Now let’s create the change function which calls the conversion function.



        function change(name) {
                b = document.getElementById("binary").value;
                conversion = bin_dec(b);
          
                result.value = conversion;
        }

Clearly this is one of the methods for the binary to decimal system in JavaScript, write your method in the comments below.

Some useful links

Indice argomenti tutorial JavaScript

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

15 puzzle game

Inlcudes() String Method

JavaScript array includes()

Math.random

parseInt JavaScript

Test Python

Test Python

Here is a test to evaluate the skills acquired on the Python language, specifically this is a quiz about the lambda function.

Evaluate your skills on basic and advanced Python concepts with tests created on Creative Coding.

27
Created on By Cristina

Python Lambda function Quiz

1 / 5

What will be the output of this code?

list_number = [11,8,4,5]
new_list = list(filter(lambda x: x > 5, list_number))
print(new_list)

2 / 5

What will be the output of this code?
list_number = [11,-8,4,-5]
my_number = [number for number in list_number if number > 0]
print(my_number)

3 / 5

What will be the output of this code?

f1 = lambda x : x + 2
f2 = lambda x: x * 2

y = 2

y = f1(y)
y = f2(y)
y = f1(y)

print(y)

4 / 5

What will this program print?
list_number = [11,8,4,5]
new_list = list(map(lambda x: x%2==0, list_number))
print(new_list)

5 / 5

What will be the output of this code?
f_cube = lambda x : x * x * x
f_square = lambda x: x * x

y = 2

y = f_square(y)
y = f_cube(y)

print(y)

Your score is

The average score is 69%

0%

 

Write in the comments any doubts or difficulties or if something is wrong in your opinion!
Follow our tutorial to always learn new concepts at the following link: https://www.codingcreativo.it/en/python-tutorial/

Here are some useful links you can find on the blog:

Python lambda function

Use Python dictionaries

Python readline()

Python max()

Break Python

Insertion Sort

Merge Sort

Quick Sort

Factorial

Factorial

In this lesson we will calculate the factorial of a number in Python using various methods.

First let’s give the definition.

In mathematics, the factorial of a natural number n is the product of positive integers less than or equal to this number and is denoted by n!

So for example 5! = 5 * 4 * 3 * 2 * 1 = 120

while by convention 0! = 1

Python Factorial

Let’s now create a program for calculating the factorial in Python.

We take as input n and set the variable f equal to 1, that is, the neutral element of the multiplication.

Then, with a for loop that has the index i that varies from a range of 1 to n + 1, we calculate the factorial by performing this operation f = f * i.

So if for example n is equal to 5 we will have these steps:

f = 1 * 1, f = 1 * 2, f = 2 * 3, f = 6 * 4, f = 24 * 5

In output we will therefore print 120.

A possible implementation of the algorithm can therefore be this:


n=int(input('Insert a number: '))
f=1

for i in range(1,n+1):
    f*=i
    
print(n)

Recursive solution to the factorial

We can also find a recursive solution. Let’s first give the definition.

A function that calls itself is called recursive.

The recursive technique allows you to write elegant algorithms, but it is not always the most efficient solution. This is due to the fact that recursion is implemented with functions and the invocation of a function clearly has a significant cost.

We therefore define a function and inside we first check if n is equal to 0, returning the value 1. Otherwise we multiply n by the factorial of n-1.

We therefore propose the second solution to the computation of the factorial in Python which makes use of recursion.


n = int(input('Insert a number: '))

def fact_number(n):
    if n == 0:
        return 1
    else:
        return n * fact_number(n-1)

print('Factorial: ', fact_number(n))

Some useful links

Python tutorial

Python Compiler

Install Python

Variables