Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to show price with 2 decimal places

I have a form that has 5 fields for a user to put how much they want to pay for 5 separate items. I then have it automatically totaling it at the bottom. Since this total goes to a payment gateway I need to force it to round to 2 decimal places.

Can someone tell me how to change the code to do this? I am a newbie with this.

Here is the code I have:

<script>
    function calculatepay(pay) {
var one = document.getElementById(pay + 'Student1Total').value;
var two = document.getElementById(pay + 'Student2Total').value;
var three = document.getElementById(pay + 'Student3Total').value;
var four = document.getElementById(pay + 'Student4Total').value;
var five = document.getElementById(pay + 'Student5Total').value;

var payTotal = document.getElementById(pay + 'payTotal');
payTotal.value = Number(one) + Number(two) + Number(three) + Number(four) + Number(five) ;
    calculateTotal();
}


</script>


<input type="text" id="pay1Student1Total" name="data1" onKeyUp="calculatepay('pay1');" /><br />
<input type="text" id="pay1Student2Total" name="data2" onKeyUp="calculatepay('pay1');" /><br />
<input type="text" id="pay1Student3Total" name="data3" onKeyUp="calculatepay('pay1');" /><br />
<input type="text" id="pay1Student4Total" name="data4" onKeyUp="calculatepay('pay1');" /><br />
<input type="text" id="pay1Student5Total" name="data5" onKeyUp="calculatepay('pay1');" /><br /><br /><br />
Total: 
<input type="text" id="pay1payTotal" onKeyUp="calculateTotal();" value="0"/><br /><br />
like image 742
user3062396 Avatar asked Oct 26 '25 10:10

user3062396


1 Answers

You can use the toFixed(2) function in JavaScript to convert numbers to a fixed value.

It's used like this:

payTotal.value.toFixed(2)

So if the input value is 1, it'll look like 1.00

like image 120
Nemesis02 Avatar answered Oct 29 '25 00:10

Nemesis02