Javascript to show price with 2 decimal places - javascript

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 />

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

You can use .toFixed() method :
var x = 5.1232;
console.log(x.toFixed(2));

Use this : toFixed(2); It will round to two decimal places

You can use Math.round(num * 100) / 100

Related

Is there a way to limit the number of decimal characters in an input when its used as a result box?

I'm making a simple html where i make calculations based on different inputs and presenting the results in other inputs using pure js.
In the below example where i divide a / b input and return the result in c,lets say you put 633 / 33 it returns a number like this : 19.181818181818183
Is there a way to make look like 19.18 ?
Using the maxlength Attribute to the result input wont work as it limits the number of characters you can type in,not the number of characters you can send to.
<input type="text" id="input1" style="width: 100px " onkeyup='divide_numbers()'/>
<label> / </label>
<input type="text" id="input2" style="width: 100px " onkeyup='divide_numbers()'/>
<label> = </label>
<input type="text" id="result" style="width: 100px "/>
<script>
function divide_numbers() {
var first_number = parseFloat(document.getElementById("input1").value) ;
var second_number = parseFloat(document.getElementById("input2").value) ;
document.getElementById("result").value=first_number/second_number ;
}
</script>
You can use +number.toFixed(2), which will first create a string with two digits after the decimal point and then coerce it back to a number, removing unnecessary decimal digits.
function add_numbers() {
var first_number = parseFloat(document.getElementById("input1").value) ;
var second_number = parseFloat(document.getElementById("input2").value) ;
document.getElementById("result").value = +(first_number/second_number).toFixed(2);
}
<input type="text" id="input1" style="width: 100px " onkeyup='add_numbers()'/>
<label> / </label>
<input type="text" id="input2" style="width: 100px " onkeyup='add_numbers()'/>
<label> = </label>
<input type="text" id="result" style="width: 100px "/>

DOM/Javascript not returning a value, results yield NAN. Can't find the error?

I have a logic error and cant seem to find it. I think I am "getting" the elements by ID correctly, but it yields NAN. Any help with this is appreciated.
I am not sure what else I am doing wrong, any suggestions are welcome. I am new to DOM and not very familiar with Javascript.
var avgGrade
function calcAvg()
{
avgGrade = document.getElementById("finalExam") +
document.getElementById("homework") + document.getElementById("projects");
alert("Your average is " + avgGrade);
document.getElementById("stuAverage").value = avgGrade;
}
//-->
</script>
</head>
<body>
<h1>Calculate average</h1>
<h3>Enter the following information and then press the <b>AVERAGE</b> button
to calculate
your grade.</h3>
<p>To clear the data fields, click here <b>Refresh this page</b></p>
<form action="#" name="gradeInfo" id="gradeInfo">
<p>
Enter Final Exam Grade:
<input type="text" name="finalExam" id="finalExam" size="4" /><br />
Enter Homework Grade:
<input type="text" name="homework" id="homework" size="4" /><br />
Enter Projects Grade:
<input type="text" name="projects" id="projects" size="4" /><br />
<br /><br />
<input type="button" value="AVERAGE" onclick="calcAvg()" />
<br /><br />
Your Average is:
<input type="text" name="stuAverage" id="stuAverage" size="4" /><br />
</p>
</form>
</body>
</html>
First missing a ; at the end of var avgGrade
Second you need to get values of the inputs not the inputs itself.
document.getElementById("homework").value
Third you need to convert the values from string to integer using parseInt
avgGrade = parseInt(document.getElementById("finalExam").value) +
parseInt(document.getElementById("homework").value) +
parseInt(document.getElementById("projects").value);
jsfiddle DEMO
P.s. you gotta divide it to the number of grades to get the average.
to get the value in the input field you need to write -
document.getElementById("finalExam").value

Using Javascript to calculate form fields -- get NaN as a result

I have created a short form that is supposed to calculate values based on user input. I've got most of it figured out but can't seem to get the results to show up in the totals field. Instead, I get NaN.
I'm trying to use parseInt but haven't had any luck yet.
Here is what I have so far:
The Javascript:
var AdPrice = document.getElementsByTagName('input') = 0;
var ColorCharge = document.getElementsByTagName('input') = 0;
var WebAd = document.getElementsByTagName('input') = 0;
var AdSubtotal = 0;
var DownPayment = document.getElementsByTagName('input') = 0;
var TotalPrice = 0;
var Payments = document.getElementsByTagName('input') = 0;
var TotalPayment = 0;
function updateTotal()
{
var subtotal = AdPrice + ColorCharge + WebAd;
var total = subtotal - DownPayment;
var totalmonthlypayment = total / Payments;
parseFloat(document.getElementById('AdSubtotal').value = subtotal);
parseFloat(document.getElementById('TotalPrice').value = total);
parseFloat(document.getElementById('Payment').value = totalmonthlypayment);
}
The HTML:
<fieldset>
<legend>Payment Details</legend>
Ad Charge $
<input type="text" name="AdPrice" id="AdPrice" class="medium" onChange="updateTotal()" /><br />
Color Charge +
<input type="text" name="ColorCharge" id="ColorCharge" class="medium" onChange="updateTotal()" /><br />
Web Ad +
<input type="text" name="WebAd" id="WebAd" class="medium" onChange="updateTotal()" /><br />
Subtotal =
<input type="text" name="AdSubtotal" id="AdSubtotal" readonly class="medium" /><br />
Down Payment -
<input type="text" name="DownPayment" id="DownPayment" class="medium" onChange="updateTotal()" /><br />
Total =
<input type="text" name="TotalPrice" id="TotalPrice" readonly class="medium" /><br /><br />
# Consec. Payments \
<input type="text" name="Payments" id="Payments" class="medium" onChange="updateTotal" /><br />
Amt Each Payment $
<input type="text" name="Payment" id="Payment" class="medium" readonly /><br /><br />
<input type="checkbox" name="ProratedCheck" id="ProratedCheck" /> <span style="margin-right:10px;">Prorated/Length</span><input type="text" name="ProratedLength" id="ProratedLength" />
</fieldset>
I also have a fiddle:
http://jsfiddle.net/kjetterman/eHQV4/10/
There were several errors on the javascript that you need to work on, as mentioned on the comments for your question you should use getElementById for retrieving DOM elements, other issue you had is that your code was running as soon as the browser gets the response which at the moment might not have the DOM ready for work so all your references were coming back as NULL. Here's the working version, you still need to add some validation for when the initial values are zeroes so you don't get NaN as result of operations.
http://jsfiddle.net/Wy7kE/2/
Division by zero (subtotal) at the beginning.
And:
Does this kind of binding work? I think not. Very new to me.......
What about placing the "getElements"-lines inside the method?

Javascript equation with negative and positive numbers

I have four text input fields, after the user enters relevant values, I have to make a JavaScript calculation to add all of them
I use:
var total = Number(value1) + Number(value2) + Number(value3) + Number(value4);
then I display the total:
document.getElementById("value5").innerHTML = total;
If one of the values is negative, it gets added as a positive number. How do I get the equation to treat it as a negative one (so it gets subtracted)?
I dont know what the problem is but it works well
<script type="text/javascript">
function fnc(){
val1=Number(document.getElementById("t1").value);
val2=Number(document.getElementById("t2").value);
var total = val1+val2;
document.getElementById("t3").value=total;
}
</script>
input1: <input type="text" id="t1" />
input2: <input type="text" id="t2" />
<br />
<input type="text" id="t3" />
<input type="button" id="btn" onclick="fnc()" value="click me" />

Subtract an integer from a calculated total

I've built a script to add quantities/units and generate a total that displays sales tax.
How can I get this calculator to recognise #discount and subtract it from the total before the GST (10% sales tax) is calculated and added?
Also, is it possible to generate the total when the page loads? Instead of a user having to press the 'Generate total' button?
HTML
<ul>
<li> Item 1 (<input type="text" name="others" size="4" value="5" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 2 (<input type="text" name="others" size="4" value="1" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 3 (<input type="text" name="others" size="4" value="3" readonly="readonly" class="readonly_field"/> units)</li>
</ul>
<input type="button" value="Generate Total" onclick="total()" /><br><br>
Discount <input type="text" id="discount" name="discount" value="500"/><br><br>
Total Units: <input type="text" id="units_total" name="units_total" readonly="readonly" /><br>
Sub Total: <input type="text" id="sub_total" name="sub_total" readonly="readonly" /><br>
Includes GST: <input type="text" id="gst_total" name="gst_total" readonly="readonly" /><br>
Total: <input type="text" id="g_total" name="g_total" readonly="readonly" />
JS
function total(){
var total_value = 0;
var all_others = document.getElementsByTagName("input");
for(var i=0; i<all_others.length; i++){
if(all_others[i].type!="text" || all_others[i].name!="others"){
continue;
}
total_value += parseFloat(all_others[i].value);
}
document.getElementById("units_total").value = (total_value).toFixed(1);
document.getElementById("sub_total").value = ((total_value) *100).toFixed(2);
document.getElementById("g_total").value = (((total_value * 10/100) + total_value) * 100).toFixed(2);
document.getElementById("gst_total").value = ((total_value * 10/100) * 100).toFixed(2);
}
Firstly, to get your function to execute on window load, wrap it in a load event:
window.onload = function() {
total();
}
Secondly, to get it to figure in discount, you just need to modify your variable a few times, but then when adding them together, make sure you parse them with .parseFloat():
if (document.getElementById('discount').value != '') {
var discount = document.getElementById('discount').value;
}
else {
var discount = 0;
}
var sub_total = (((total_value) * 100).toFixed(2) - discount).toFixed(2);
var gst = ((total_value * 10 / 100) * 100).toFixed(2);
document.getElementById("sub_total").value = sub_total;
document.getElementById("gst_total").value = gst;
document.getElementById("g_total").value = (parseFloat(sub_total) + parseFloat(gst)).toFixed(2);
DEMO
First of all, I suggest you to perform validation and computations both server side and client side. The first ensures security while the second improves the responsiveness of the UI.
Said that, you'd better introduce several support variables and perform computation on them. You should get the value from the elements you are interested into using getElementById and store it in variables.
Then you should perform computation on that variables and finally place the results in the elements you want to use to display them to the user.
To perform the operation when the page loads have a look at this.

Categories

Resources