What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
La meilleure approche pour une calculatrice simple est de séparer clairement les responsabilités : HTML construit l’interface, CSS la rend lisible et JavaScript gère l’état ainsi que les opérations. L’exemple ci-dessous fonctionne sans framework, accepte la souris et le clavier, gère les décimales, Backspace, Escape et affiche une erreur en cas de division par zéro.
Préparer les fichiers
Créez trois fichiers dans le même dossier :
index.html
style.css
calculator.js
Ouvrez ensuite index.html dans un navigateur. Pour charger le JavaScript après l’analyse du HTML, utilisez l’attribut defer :
<script src="calculator.js" defer></script>
Construire l’interface HTML
Utilisez de vrais éléments <button> plutôt que des <div> cliquables. Ils possèdent déjà une sémantique adaptée aux actions et peuvent recevoir le focus au clavier. Les attributs data-action et data-value permettent à JavaScript de savoir quelle action effectuer.
Recommended Free Tools
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Calculatrice simple</title>
<link rel="stylesheet" href="style.css">
<script src="calculator.js" defer></script>
</head>
<body>
<main class="calculator" aria-label="Calculatrice">
<output id="display" class="calculator__display" aria-live="polite">0</output>
<div class="calculator__keys">
<button type="button" data-action="clear">C</button>
<button type="button" data-action="delete" aria-label="Supprimer le dernier chiffre">⌫</button>
<button type="button" data-action="operator" data-value="/">÷</button>
<button type="button" data-action="operator" data-value="*">×</button>
<button type="button" data-action="digit" data-value="7">7</button>
<button type="button" data-action="digit" data-value="8">8</button>
<button type="button" data-action="digit" data-value="9">9</button>
<button type="button" data-action="operator" data-value="-">−</button>
<button type="button" data-action="digit" data-value="4">4</button>
<button type="button" data-action="digit" data-value="5">5</button>
<button type="button" data-action="digit" data-value="6">6</button>
<button type="button" data-action="operator" data-value="+">+</button>
<button type="button" data-action="digit" data-value="1">1</button>
<button type="button" data-action="digit" data-value="2">2</button>
<button type="button" data-action="digit" data-value="3">3</button>
<button type="button" data-action="equals" class="key--equals">=</button>
<button type="button" data-action="digit" data-value="0" class="key--zero">0</button>
<button type="button" data-action="decimal">.</button>
</div>
</main>
</body>
</html>
type="button" empêche un bouton d’envoyer accidentellement un formulaire si la calculatrice est réutilisée dans ce contexte.
#1 Best Overall
- Fundamental, two-line calculator that combines statistics and advanced scientific functions for high school math and science
- Two-line display shows the entry and calculated result at the same time for easy understanding of the calculation
- Fraction features, conversions, and basic scientific and trigonometric functions
- Solar and battery powered
- Approved for use on SAT, ACT and AP exams
Ajouter le style CSS
:root {
font-family: system-ui, sans-serif;
color-scheme: light dark;
}
.calculator {
width: min(calc(100% - 2rem), 20rem);
margin: 2rem auto;
}
.calculator__display {
display: block;
min-height: 3rem;
padding: .75rem 1rem;
margin-bottom: .75rem;
overflow-x: auto;
text-align: right;
font-size: 2rem;
background: #222;
color: #fff;
border-radius: .5rem;
}
.calculator__keys {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: .5rem;
}
button {
min-height: 3rem;
padding: .75rem;
border: 0;
border-radius: .5rem;
font-size: 1.1rem;
cursor: pointer;
}
button:focus-visible {
outline: 3px solid #4c9ffe;
outline-offset: 2px;
}
.key--zero { grid-column: span 2; }
.key--equals { grid-row: span 2; }
Comprendre l’état de la calculatrice
La saisie actuelle reste une chaîne afin de gérer correctement le point décimal, le zéro initial et la suppression d’un caractère. Elle est convertie en nombre uniquement lorsqu’une opération doit être calculée.
let currentInput = "0";
let firstOperand = null;
let operator = null;
let waitingForSecondOperand = false;
let hasError = false;
Pour 12 + 7, l’application conserve par exemple firstOperand = 12, operator = "+" et la saisie actuelle 7. Cette structure est plus prévisible qu’une expression textuelle à interpréter.
Rank #2
- 10-digit display; for general math, pre-algebra, algebra 1 and 2, trigonometry and biology
- Performs trigonometric functions, logarithms, roots, powers, reciprocals, and factorials
- Also add, subtract, multiply and divide fractions; 1-variable statistics (mean / standard deviation)
- Conversions: fractions/decimals, degrees/radians/grads, DMS/decimal/degrees, and polar/rectangular
- Battery-powered; includes slide case
Le JavaScript complet, sans eval()
const calculator = document.querySelector(".calculator");
const display = document.querySelector("#display");
let currentInput = "0";
let firstOperand = null;
let operator = null;
let waitingForSecondOperand = false;
let hasError = false;
function updateDisplay() {
display.textContent = currentInput;
}
function resetCalculator() {
currentInput = "0";
firstOperand = null;
operator = null;
waitingForSecondOperand = false;
hasError = false;
updateDisplay();
}
function showError(message) {
currentInput = message;
hasError = true;
firstOperand = null;
operator = null;
waitingForSecondOperand = false;
updateDisplay();
}
function inputDigit(digit) {
if (hasError) resetCalculator();
if (waitingForSecondOperand) {
currentInput = digit;
waitingForSecondOperand = false;
} else if (currentInput === "0") {
currentInput = digit;
} else {
currentInput += digit;
}
updateDisplay();
}
function inputDecimal() {
if (hasError) resetCalculator();
if (waitingForSecondOperand) {
currentInput = "0.";
waitingForSecondOperand = false;
} else if (!currentInput.includes(".")) {
currentInput += ".";
}
updateDisplay();
}
function deleteLastCharacter() {
if (hasError || waitingForSecondOperand) return;
currentInput = currentInput.length > 1
? currentInput.slice(0, -1)
: "0";
if (currentInput === "-") currentInput = "0";
updateDisplay();
}
function calculate(a, b, selectedOperator) {
switch (selectedOperator) {
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/": return b === 0 ? null : a / b;
default: return b;
}
}
function formatResult(value) {
if (!Number.isFinite(value)) return null;
// Compromis d'affichage : ce n'est pas une précision financière.
return String(Number(value.toPrecision(12)));
}
function handleOperator(nextOperator) {
if (hasError) {
resetCalculator();
return;
}
const inputValue = Number(currentInput);
if (!Number.isFinite(inputValue)) {
showError("Erreur");
return;
}
if (operator && waitingForSecondOperand) {
operator = nextOperator;
return;
}
if (firstOperand === null) {
firstOperand = inputValue;
} else if (operator) {
const result = calculate(firstOperand, inputValue, operator);
if (result === null) {
showError("Division par zéro");
return;
}
const formatted = formatResult(result);
if (formatted === null) {
showError("Erreur");
return;
}
currentInput = formatted;
firstOperand = result;
}
operator = nextOperator;
waitingForSecondOperand = true;
updateDisplay();
}
function handleEquals() {
if (hasError || operator === null || firstOperand === null) return;
const secondOperand = Number(currentInput);
const result = calculate(firstOperand, secondOperand, operator);
if (result === null) {
showError("Division par zéro");
return;
}
const formatted = formatResult(result);
if (formatted === null) {
showError("Erreur");
return;
}
currentInput = formatted;
firstOperand = null;
operator = null;
waitingForSecondOperand = true;
updateDisplay();
}
calculator.addEventListener("click", (event) => {
const button = event.target.closest("button");
if (!button) return;
const { action, value } = button.dataset;
switch (action) {
case "digit": inputDigit(value); break;
case "decimal": inputDecimal(); break;
case "operator": handleOperator(value); break;
case "equals": handleEquals(); break;
case "clear": resetCalculator(); break;
case "delete": deleteLastCharacter(); break;
}
});
document.addEventListener("keydown", (event) => {
const { key } = event;
if (/^d$/.test(key)) return inputDigit(key);
if (key === ".") return inputDecimal();
if (["+", "-", "*", "/"].includes(key)) return handleOperator(key);
if (key === "Enter" || key === "=") {
event.preventDefault();
return handleEquals();
}
if (key === "Escape") return resetCalculator();
if (key === "Backspace") return deleteLastCharacter();
});
updateDisplay();
Pourquoi éviter eval() ?
Une solution comme display.textContent = eval(display.textContent) est courte, mais elle exécute une chaîne comme du code JavaScript. Si cette chaîne est influencée par une source non fiable, elle peut permettre l’exécution d’instructions arbitraires. MDN recommande de ne pas utiliser directement eval() : documentation MDN sur eval().
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Cette approche rend également la validation, la gestion des erreurs et l’explication de l’algorithme plus difficiles. La solution proposée calcule uniquement quatre opérateurs connus. Elle est donc plus sûre et plus adaptée à un projet pédagogique. Les gestionnaires inline comme onclick sont aussi moins faciles à maintenir ; addEventListener() sépare mieux HTML et JavaScript. Voir la documentation MDN sur les événements.
Rank #3
- View multiple calculations at the same time: Compare results and explore patterns on-screen with the MultiView display that supports up to four lines
- See math exactly as it appears in textbooks: Display math expressions, symbols and stacked fractions exactly the way they appear in textbooks — no need to adapt to a technical syntax; provides quick access to frequently used functions
- Scientific notation output: View scientific notation with the proper superscripted exponents and see the output in scientific notation
- Explore (x,y) table of values: Students can easily explore an (x,y) table of values for a given function automatically or by entering specific x values
- The TI-30XS MultiView scientific calculator is ideal for general math, Pre-Algebra, Algebra 1 and 2, Geometry, Statistics, general science, Biology and Chemistry
Tester la calculatrice
2 + 3 =doit afficher5.9 - 4 =doit afficher5.6 × 7 =doit afficher42.8 ÷ 2 =doit afficher4.0.1 + 0.2 =doit afficher une valeur raisonnablement formatée.5 ÷ 0 =doit afficherDivision par zéro.123, puis⌫, doit afficher12.- Plusieurs pressions sur
.ne doivent pas ajouter plusieurs séparateurs. - Les touches numériques, opérateurs,
Enter,EscapeetBackspacedoivent fonctionner. - La touche Tab doit parcourir les boutons et le focus doit rester visible.
En cas de problème, ouvrez les outils de développement et vérifiez la console, le chargement de calculator.js, les sélecteurs .calculator et #display, ainsi que la correspondance entre data-action, data-value et le code JavaScript. Un script chargé avant le DOM peut échouer ; defer évite généralement ce problème. Consultez la documentation MDN sur le chargement de JavaScript.
Limites et améliorations possibles
Cette version effectue principalement une opération à la fois. Elle n’interprète donc pas une expression complète comme 2 + 3 × 4 avec priorité opératoire, et ne gère pas les parenthèses ni l’historique. Pour ces fonctions, il faut construire un analyseur d’expressions : tokenisation, priorité des opérateurs et, par exemple, algorithme Shunting Yard.
Rank #4
- Professional Grade Scientific Calculator With 240 Scientific Functions.
- 10+2-Digit Widescreen HD Display
- It Has 2-Line Display Shows Entry And Calculated Result At Same Time
- Protective Hardcover Prevents Scratches And Dings
- Meets The Ergonomics Design And Offers A Comfortable Grip, Manufacture Recommended Age +3 Years, CPSIA : No Warning Applicable
JavaScript utilise des nombres flottants binaires. Des calculs comme 0.1 + 0.2 peuvent donc produire une petite différence interne. Le formatage à 12 chiffres améliore l’affichage, mais ne transforme pas cette calculatrice en outil financier. Pour la comptabilité, utilisez des unités entières comme les centimes ou une stratégie décimale spécialisée.
Les extensions naturelles sont un bouton +/-, le pourcentage, le modulo, les mémoires, la copie du résultat, un thème sombre et des tests automatisés. Chaque ajout doit conserver une validation explicite plutôt que transmettre une expression à eval().
Quick Recap
Best Value
- SAT Exam Ready: 240 functions, ideal school calculator for SATs. Supports trigonometry, statistics with 1-2 variable calculations, 3 angle modes (degrees, radians, grads), and engineering modes.
- Compact & Durable: Lightweight, ergonomic scientific calculator, ideal for exams, office, or daily use. Responsive buttons, clear labels, hard cover protection. Uses 2 AAA batteries, 6-month warranty.
- Basic & Versatile: This non programmable calculator handles essential math functions with a 12-digit HD display. Pre-defined functions, school and office calculators, perfect for non-graphing tasks.
- Enhanced Display & Versatile: The 2-line display shows entries & results for clarity. Ideal high school calculator for chemistry, physics, stats, & calculus, perfect for academic & business use.
- Trigonometry & Algebra Specialist: This non graphing calculator has trig functions (sin, cos, tan) & logs (log, ln), ideal for geometry, algebra & advanced calculations. Great for sixth-form students.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

