Skip to main content

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

  1. Declare a variable called price and assign it a numeric value, representing the price of a product.

  2. Declare a variable calledivawith the value0.21which represents 21% VAT.

  3. Calculate the total price by adding the initial price and the VAT amount (multiply theprecio by ivand add it toprecio), and stores the result in a variable called totalPrice.

  4. Displays theprecioTotalon the console.

Solution

Step 1: Create the index.html file

HTML
<!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

JavaScript
// 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);
info

🔎Check the sectionData Types in JavaScript: A Complete Guide with Practical Exampleswhere you will find more information on this topic.