In: Computer Science
JS Bin / Tax Calculator / using HTML | CSS | JavaScript
-------------------------------------------------------------------------------------------
How can I edit the JavaScript below so that when the calculate button is clicked the total price only shows two decimal places by using the toFixed() method?
-----------------------------------------------------------------------------------------------------------
JavaScript:
// Variables
var tax = "tax"; // Tax percentage
var taxRate = document.getElementById('tax'); // Selecting tax
element
// On the time of loading the DOM we are setting the tax
rate
window.addEventListener('DOMContentLoaded', (event) => {
taxRate.value = tax;
});
// Calculate button
var btn = document.getElementById('calculate');
btn.addEventListener('click', (event) => {
// Stopping form to submit data
event.preventDefault();
// Selecting dom elements
var quantity = document.getElementById('quantity').value;
var price = document.getElementById('price').value;
var discount = document.getElementById('discount').value;
var total = document.getElementById('total');
// Calculating the total price
var totalPrice = quantity * price;
var totalTax = (totalPrice * taxRate.value) / 100;
var totalDiscount = (totalPrice * discount) / 100;
var finalPrice = totalPrice + totalTax - totalDiscount;
// Setting the total amount
total.value = finalPrice;
});
you have to add this line before the line
"total.value=finalPrice;
Syntax
number.toFixed(number of decimal place)
NOW ADD THIS LINE
finalprice.toFixed(2);
Here is the updated code
// Variables
var tax = "tax"; // Tax percentage
var taxRate = document.getElementById('tax'); // Selecting tax
element
// On the time of loading the DOM we are setting the tax
rate
window.addEventListener('DOMContentLoaded', (event) => {
taxRate.value = tax;
});
// Calculate button
var btn = document.getElementById('calculate');
btn.addEventListener('click', (event) => {
// Stopping form to submit data
event.preventDefault();
// Selecting dom elements
var quantity = document.getElementById('quantity').value;
var price = document.getElementById('price').value;
var discount = document.getElementById('discount').value;
var total = document.getElementById('total');
// Calculating the total price
var totalPrice = quantity * price;
var totalTax = (totalPrice * taxRate.value) / 100;
var totalDiscount = (totalPrice * discount) / 100;
var finalPrice = totalPrice + totalTax - totalDiscount;
//fixed number of decimal point
finalPrice.toFixed(2);
// Setting the total amount
total.value = finalPrice;
});