I have a table that does a multiplication of qty by price returning a line item total then a total for all the line items.
I need the results to be in two decimal places. (bonus points if there is a way to return with the dollar sign but from what I can find that isn’t an option.)
Scripts I am using below.
I am attempting to use the .toFixed(2) But can’t seem to find where to put it correctly without cracking my current scripts. (Self taught so please dumb it down for me 🙂 )
<script>
function total_amount(){
var table = document.getElementById('line_item');
for(var i=1;i<table.rows.length;i++){
qty = table.rows[i].cells[1].getElementsByTagName("input")[0].value
unit = table.rows[i].cells[2].getElementsByTagName("input")[0].value
table.rows[i].cells[3].getElementsByTagName("input")[0].value = qty * unit;
}
}
</script>
2
Answers
You can use the toFixed() method to format the result of the multiplication operation to two decimal places. Here’s an updated version of your script that includes this change:
This should update the value in the fourth column of each row with the result of the multiplication, rounded to two decimal places. If you also want to add a dollar sign to the results, you can concatenate it to the total value like this:
This will add the dollar sign at the beginning of the string representing the total value.
You can use the internationalization (i18n) currency formatter:
Also, you should separate your table head and body. This way you don’t need to arbitrarily skip the first row.