Seleziona una pagina

## 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.

``````

<div class="content">
</div>
<div class="content">
<div class="content">
<input type="submit" id="7" value="7" onclick="n(this.id)" class="key">
<input type="submit" id="8" value="8" onclick="n(this.id)" class="key">
<input type="submit" id="9" value="9" onclick="n(this.id)" class="key">
<input type="submit" id="/" value="/" onclick="n(this.id)" class="key">
</div>
<div class="content">
<input type="submit" id="4" value="4" onclick="n(this.id)" class="key">
<input type="submit" id="5" value="5" onclick="n(this.id)" class="key">
<input type="submit" id="6" value="6" onclick="n(this.id)" class="key">
<input type="submit" id="*" value="X" onclick="n(this.id)" class="key">
</div>
<div class="content">
<input type="submit" id="1" value="1" onclick="n(this.id)" class="key">
<input type="submit" id="2" value="2" onclick="n(this.id)" class="key">
<input type="submit" id="3" value="3" onclick="n(this.id)" class="key">
<input type="submit" id="-" value="-" onclick="n(this.id)" class="key">
</div>
<div class="content">
<input type="submit" value="C" onclick="reset_all()" class="key">
<input type="submit" id="0" value="0" onclick="n(this.id)" class="key">
<input type="submit" id="." value="." onclick="n(this.id)" class="key">
<input type="submit" id="+" value="+" onclick="n(this.id)" class="key">
</div>
<div class="content">
<button value="=" onclick="op()" class="egual key">=</button>
</div>
</div>

``````

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.

Tutorial JavaScript

## Test JavaScript

Ecco un test per valutare le competenze acquisite sul linguaggio JavaScript.

Valuta le tue competenze su concetti di base ed avanzati di JavaScript con i test creati su Coding Creativo.

[ays_quiz id=’2′]

Scrivi nei commenti eventuali dubbi o difficoltà o se c’è qualcosa di errato secondo voi!

Segui il nostro tutorial per apprendere sempre nuovi concetti al seguente link tutorial JavaScript!

Ecco alcuni link utili che puoi trovare sul blog:

Metodo includes

Proprietà length

Gioco indovina numero in JavaScript

Semplice quiz utilizzando gli array

Come sviluppare il gioco del 15 in JavaScript

Gioco della slot machine in JavaScript

Memory Game in JavaScript

Funzioni JavaScript e istruzione return

Funzioni di callback

Esempi funzioni di callback

Callback e setTimeout

## 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:

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.

``````

<div>
<label>Decimal: </label>
<input type="text" id="decimal" onkeyup="change(this)"></div>
<div>
<label>Binary:</label>
</div>
<div>
<label>Octal:</label>
</div>
<div>
</div>

``````

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.

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

## 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:

``````

<div>
<label>Binary: </label>
<input type="text" id="binary" onkeyup="change(this)" onkeypress="return isValidNumber(event)">
</div>
<div>
<label>Decimal:</label>
</div>

``````

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 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.

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

## Conversione binario decimale

In questa lezione svilupperemo un sistema di conversione da binario a decimale in JavaScript.

Innanzitutto proviamo il simulatore sotto. Inseriamo nel campo di input un numero binario, in automatico nel campo sotto si vedrà il corrispettivo numero decimale.

Decimale:

## Conversione da binario a decimale in JavaScript

Innanziutto impostiamo la parte di codice inerente l’HTML.

Nel nostro caso saranno semplicemente due caselle di input:

``````

<div><label>Binary: </label>
<input type="text" id="binary" onkeyup="change(this)" onkeypress="return isValidNumber(event)"></div>

``````

Ho inserito sulla casella di input in ingresso, ovvero quella dove scriveremo il numero binario, due eventi:

• onkeyup che utilizzo per attivare la funzione change;
• onkeypress che utilizzo per controllare se il numero è valido.

Chiaramente potrei gestire anche diversamente questi eventi lato JavaScript.

Sviluppiamo quindi la funzione isValidNumber, la quale verifica che il numero in ingresso sia 0 oppure 1. In questo modo se proviamo a digitare altri numeri o lettere non verranno presi in considerazione.

``````
function isValidNumber(e) {

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

return false;
}
``````

Sviluppiamo adesso una funzione che consente di trasformare in decimale il numero binario preso in considerazione.

Seguiamo questo metodo:

• Trasformiamo in una lista il numero inserito nel campo di input con id binario;
• Invertiamo la lista;
• Applichiamo il metodo forEach per scorrere la lista.
• Dunquem, per ogni elemento controlliamo che il numero sia 1. Se la condizione è soddisfatta si aggiunge alla variabile decimale la potenza di riferimento, ottenuta grazie all’utilizzo di index.
• Si restituisce il numero decimale ottenuto.

Ecco dunque una possibile implementazione dell’algoritmo per la conversione binario decimale 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;
}
``````

Creiamo adesso la funzione change che richiama la funzione di conversione.

``````

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

result.value = conversion;
}
``````

Chiaramente questo è uno dei metodi per il sistema di conversione da binario a decimale in JavaScript, scrivete il vostro metodo nei commenti sotto.