Exercise 7: Calculating the Total Price with VAT
Learn how to implement an automatic price calculation with VAT. Ideal for e-commerce or invoicing projects using JavaScript.
The main purpose is to practice using arithmetic operators and understand how to calculate percentages in JavaScript.
Activity
-
Declare a variable called price and assign it a numeric value, representing the price of a product.
-
Declare a variable called
ivawith the value0.21which represents 21% VAT. -
Calculate the total price by adding the initial price and the VAT amount (multiply the
preciobyivand add it toprecio), and stores the result in a variable called totalPrice. -
Displays the
precioTotalon the console.
Solution
Step 1: Create the index.html file
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Calculando el Precio Total con IVA</title>
</head>
<body>
<h1>Ejercicio 7: Calculando el Precio Total con IVA</h1>
<p>Los cambios se muestran en consola.</p>
<script src="script.js"></script>
</body>
</html>
Step 2: Write the code in script.js
// Declaración de variables
let precio = 100; // Precio del producto
let iva = 0.21; // IVA del 21%
// Cálculo del precio total con IVA
let precioTotal = precio + precio * iva;
// Muestra el precio total en la consola
console.log("El precio total con IVA es: $" + precioTotal);
🔎Check the sectionData Types in JavaScript: A Complete Guide with Practical Exampleswhere you will find more information on this topic.