JavaScript - Parceint, Parcefloat, Tofixed ? Trying To Get Whole Number And Decimal Places.
I'm fairly new to programming, I just started JavaScript and I did read the rules. I am a student and will not post my code asking someone to do my homework. I just need a little guidance.
For my assignment, when a webpage is loaded, it prompts the user to enter hours worked, their pay rate and tax rate, then use a function to calculate the net weekly pay, then display all numbers on the screen. Now I have this working and it appears on the screen, but I need to limit the hours worked to a whole number and the pay and tax rates need to only show 2 digits on either side of the decimal. From searching I found a lot of information about ParceInt, ParceFloat and toFixed, but cannot get these to work. Either these are not correct or I'm not using them correctly. Below are samples of 2 of the prompts. Can someone help me with this problem? Also is it better the handle this problem at the prompt or in the function or where it writes to the screen? Code: var hours_worked = prompt ("How many hours did you work?", ""); parseInt(hours_worked); var pay_rate = prompt ("What is your pay rate?", ""); parseFloat(pay_rate); Hopefully the subject was good enough and the content descriptive to understand when I'm trying to accomplish. Brian Similar TutorialsWhen I used toFixed() method on a number, I thought that this method round a number to a specified approximation, but I got a surprising result, the number became string! 15.23689 .toFixed ( 2 ) ==> "15.24" So does it convert the number into string? Hi.. I have javascript code with computation, but I have problem in my result because it was not round off or fixed into two decimal places only. here is my code: Code: <script type="text/javascript"> function test_(cmpd) { var len_ = (document.frmMain.elements.length) - 1; for (i=0; i <= len_; i++ ) { var strPos_ = document.frmMain.elements[i].id.indexOf(cmpd) if (strPos_ != -1) { var strPos = document.frmMain.elements[i].id.indexOf("_"); var strId = document.frmMain.elements[i].id.slice(strPos + 1) + "_" + document.frmMain.elements[i].id.slice(0,strPos) // this is the computation that I need to fixed the result into two decimal places document.frmMain.elements[i].value = document.getElementById(strId).value * document.getElementById('mult').value; } } } </script> Thank you so much Hey everyone. I am looking to enforce the use of 3 decimal places in an input. I have found some scripts that do this, however, I also want to format it this way in case someone enters LESS than 3 decimal places. If a user enters 1.25, I want it formatted as 1.250 If a user enters 1 I want it formatted as 1.000 etc. Possible? Not sure where to start. Good Afternoon!!! I am writing a script that needs to show the evaluation as 2 decimal places as well as containing the comma (as in a currency format). It should be as simple as possible. Below is my current code: <html> <script language="javascript"> //function that checks the value of text boxes and radio buttons function checkit(){ while(document.form2.text1.value=="" || document.form2.text2.value=="" || document.form2.r1[0].checked!=true && document.form2.r1[1].checked!=true && document.form2.r1[2].checked!=true && document.form2.r1[3].checked!=true) { if(document.form2.text1.value=="") { alert("You did not enter a value in the first text field"); a=confirm("Click ok to continue. Click cancel to exit") if(a==false) { break; } } if((document.form2.r1[0].checked!=true)&&(document.form2.r1[1].checked!=true) &&(document.form2.r1[2].checked!=true)&&(document.form2.r1[3].checked!=true)) { alert("You did not select a mathematical operator"); a=confirm("Click ok to continue. Click cancel to exit") if(a==false) { break; } } if(document.form2.text2.value=="") { alert("You did not enter a value in the second text box"); a=confirm("Click ok to continue. Click cancel to exit") if(a==false) { break; } } } } //function calculates value of text boxes function evalit(){ var a = eval(document.form2.text1.value) var b = eval(document.form2.text2.value) if(document.form2.r1[0].checked==true) { document.form2.text3.value=eval(a+b) } if(document.form2.r1[1].checked==true) { document.form2.text3.value=eval(a-b) } if(document.form2.r1[2].checked==true) { document.form2.text3.value=eval(a*b) } if(document.form2.r1[3].checked==true) { document.form2.text3.value=eval(a/b) } } </script> <!--calculate--!> <form name=form2> Enter a number in the first text box<br> Select a mathematical operation<br> Enter a value in the second text box<br> Push the "=" button<br> The answer should appear in the third text box<br> The result MUST have 2 digits after the decimal point and <br> if the number is big enough, include the commas for thousands, millions, billions, etc.<br> <table border=1> <tr> <td><input type="text" name="text1"></td> <td><input type="radio" name="r1" value="+">+<br> <input type="radio" name="r1" value="-">-<br> <input type="radio" name="r1" value="*">*<br> <input type="radio" name="r1" value="/">/<br></td> <td><input type="text" name="text2"</td> <td valign=middle><input type="button" value="=" onClick="checkit(); evalit()"> </td> <td><input type="text" name="text3"</td> </tr> </table> </form> </html> Any assistance would be appreciated. Thank you!!! Hello: I have this js function: Code: <script type="text/javascript"> function updatesum() { document.PaymentForm.newbalance.value = (document.PaymentForm.balance.value -0) - (document.PaymentForm.paymentamount.value -0); } </script> I want to round the value of Code: document.PaymentForm.newbalance.value to two decimal points. May I request some assistance! Hello, Could someone help me with this problem? I'd like the posted result to be a number with two decimals. I know how to make this normally but not with this kind of script. Thanks very much in advance! Code: <html> <head> <script type="text/javascript"> function calcResult(){ document.getElementById('result').innerHTML = ''; var num1 = newNumber(document.getElementById('txt1').value); var num2 = 0.429; var num3 = 1; if(isNaN(num1) || isNaN(num2)){ alert('Please enter a number'); } else { document.getElementById('result').innerHTML = num1 * num2; document.getElementById('entry').innerHTML = num1 * num3; } } window.onload=function(){ document.getElementById('btnCalc').onclick = calcResult; document.getElementById('btnCalc').onclick = calcEntry; } </script> </head> <body> <p> <input type="text" id="txt1" size="5" value="" maxlength="5" /> <button id="btnCalc">Calculate</button> </p> <p> <span id="entry"></span> × 0.429 = <span id="result"></span> </p> </body> </html> Hello, I'm really new to this site and have only a 9-week knowledge of Javascript. I'm working on a project - a mock website involving a rudimentary shopping cart and one problem that has perpetually irked me and which I can't seem to solve no matter where I plunk my toFixed(2) or parseFloat is that I can't seem to get two decimals to show on the unit cost (price) if the hundreds digit is a zero. My current bit of code is: Code: <script language="JavaScript1.1"> var numitems = opener.numitems; var totcost = 0; for (i=1; i<=numitems; i++) { document.write('<tr><td>' + opener.items[i].quantity + '</td>'); document.write('<td>' + opener.items[i].desc + '</td>'); document.write('<td>' + opener.items[i].price + '</td>'); cost = (opener.items[i].price * opener.items[i].quantity).toFixed(2); cost = Math.floor(cost * 100) /100; totcost += cost; document.write("<td>" + cost.toFixed(2)); document.write("<INPUT TYPE=HIDDEN NAME='qty" + i + "'"); document.write(" VALUE='" + opener.items[i].quantity + "'>"); document.write("<INPUT TYPE=HIDDEN NAME='desc" + i + "'"); document.write(" VALUE='" + opener.items[i].desc + "'>" + "</td></tr>"); } document.write('<tr><td colspan="3"><div class="strong">Total Cost:</div></td>'); document.write('<td><div class="strong">' + totcost.toFixed(2) + '</div></td></tr>'); </script> My current website is at http://kschmitt.aiwsites.com/imd215/. If you go to All Perennials > Full Sun > and add an 'Aster' (3rd flower at the top). Then if you click "Complete Order," my problem is that the 4.40 in the unit cost only shows up as 4.4 and I don't get it. The total cost works fine and I just don't know where to put my toFixed(2). Thanks for any help in advance! Fel My code converts a running pace to speed in mph. Works fine but posts too many digits after the decmal point in my form. Tried several things but I'm new to javascript and could use some help. Thanks! Oh, my browser is IE8, but the problem is more likely me than it... --Bill <code> <!--This does not work... form.mph.value.toFixed(4) = 60 / (pmin + psec / 60); Nor this... var mph; mph=mph.toFixed(4); --> <html> <head> <script language="javascript"> function Speed(MIN, SEC, form) { var pmin = parseFloat(MIN); var psec = parseFloat(SEC); form.mph.value = 60 / (pmin + psec / 60); } function ClearForm(form) { form.input_pmin.value = ""; form.input_psec.value = ""; form.mph.value = ""; } </script> </head> <body> <form name="pace-speed" method="post"> <table style="font-size:14px; font-weight:bold;"> <tr> <td>PACE</td> <td><input type="text" name="input_pmin" size="1">:</td> <td><input type="text" name="input_psec" size="1"></td> <td width="20"></td> <td><input TYPE="button" VALUE="Speed" onClick="Speed(this.form.input_pmin.value, this.form.input_psec.value, this.form)"></td> <td width="1"></td> <td><input type="text" name="mph" size="8"></td> <td width="2"></td> <td><input TYPE="reset" VALUE="Clear" onClick="clearForm(this.form)"></td> </tr> </table> </form> </body> </html> </code> Hi, I am using a tooltip that uses the following javascript Code: <script type="text/javascript"> $(document).ready(function() { //Tooltips $(".tip_trigger").hover(function(){ tip = $(this).find('.tip'); tip.show(); //Show tooltip }, function() { tip.hide(); //Hide tooltip }).mousemove(function(e) { var mousex = e.pageX - 90; //Get X coodrinates var mousey = e.pageY - 400; //Get Y coordinates var tipWidth = tip.width(); //Find width of tooltip var tipHeight = tip.height(); //Find height of tooltip //Distance of element from the right edge of viewport var tipVisX = $(window).width() - (mousex + tipWidth); //Distance of element from the bottom of viewport var tipVisY = $(window).height() - (mousey + tipHeight); if ( tipVisX < 90 ) { //If tooltip exceeds the X coordinate of viewport mousex = e.pageX - tipWidth - 90; } if ( tipVisY < 90 ) { //If tooltip exceeds the Y coordinate of viewport mousey = e.pageY - tipHeight - 90; } //Absolute position the tooltip according to mouse position tip.css({ top: mousey, left: mousex }); }); }); </script> As you can see I have set its X position at -90 and y position at -400 so that It could be displaying well when the mouse is hover over a link and it do appear well in the testing page http://bloghutsbeta.blogspot.com/201...slidernav.html If you put your mouse over ALEX in 'A' category BUT from the same test site but in different location from above here http://bloghutsbeta.blogspot.com/201...ting-main.html if you put your mouse over ALEX under 'SIMULATION' category then you will see that the tooltip is way down. Not even that the tooltip moves away if the screen resolution changes. I changed value again and again but didn't reach any conclusion, can someone help me with this issue as what to do to fix it? Note: If you require a complete markup please let me know in comment, I considered it not required that's why I didn't added it to my post ^^ I've managed to gain decent knowledge of HTML and CSS and am now looking into Javascript, I have been following the "beginner JavaScript tutorials" that TheNewBoston does on youtube, is this the best source or would you advise using http://www.w3schools.com/??? Any other websites? Thanks Hi this is on my midterm review and I got the program down easily but I just wanted to know if there was an easy way of shortening down the answer to only 2 decimal places.possibly through division? Code: import java.util.*; public class StockSale { public static void main(String[] args) { Scanner input = new Scanner(System.in); double stockSale; // represent the stock sale price double commission; System.out.print("Please enter a the stock value price: "); stockSale = input.nextDouble(); if(stockSale < 100.00) commission = 20.00; else if (stockSale <= 999.99) commission = (20.00 + ((stockSale - 99.99)*.01)); else if (stockSale <= 9999.99) commission = (30.00 + ((stockSale - 999.99)*.005)); else if (stockSale <= 99999.99) commission = (75.00 + (( stockSale - 9999.99)*.0025)); else commission = ( 150.00 + ((stockSale - 99999.99)*.0015)); System.out.print("The commission on this stock sale is $" + commission ); } } i appreciate any help given thanks Hi , I am very new to HTML,CSS,Javascript coding. I have to add some check box in the page and there are multiple tabs in the same single page. If I select or deselect any check box, checkbox checks from all the places should be changed. Can anybody tell me how to do so using HTML,CSS, Javascript? I have a function below where every time a question is submitted, it will add a new row in the table with a textbox which allows numbers entry only. My question is that I don't know how to code these features in this function: 1: I want the text box to be between 0 and 100, so if text box contains a number which is above 100, it will automatically change the number to the maximum number which is 100. Does any one know how to code this in my function below in javascript: Code: function insertQuestion(form) { var row = document.createElement("tr"); var cell, input; cell = document.createElement("td"); cell.className = "weight"; input = document.createElement("input"); input.name = "weight_" + qnum; input.onkeypress = "return isNumberKey(event)"; cell.appendChild(input); row.appendChild(cell); } Hi, I'm really new to Javascript. Recently in my IT class, we made a HTML page which would open a popup box, where the user could enter a key word. When the user pressed enter, the page would navigate to a specific page. The code we used was: Code: <script language = "JavaScript"> where = window.prompt ("Please tell me where you would like to go."); switch (where){ case "Digg" : window.location = "http://www.digg.com" ; break; default: window.location = "http://www.google.com" ; } </script> What I am hopeing to do, is implement this code on my workplaces server, and have the keywords link to other html documents within the server. However when I tested this, for some reason the links are not working. Can this actually be done? Am I missing something silly? Are there any other ways of doing this? Thanks in advance I am trying to figure out how to make a random number I can plug into a script count down from that number at certain times of the day until it reaches 0. I would like it to reset itself at midnight every day. I'm trying to make it work with a script I found on here that resets itself at midnight every day. So instead of it counting down too fast, it would count down to the next number after a randomly generated number of minutes until it reaches 0. But it wouldn't necessarily have to end at 0 at midnight. It could go from 845 to 323 at the end of the day at a slower pace. Is that possible?
Dear All, I can check now a field is isNumeric via this method var isNumeric = /^[0-9.]+$/;. My problem now user can put two or more decimal and I want to limit just to single decimal and only 2 numbers before the decimal? How to edit please? The way I have my code now inorder to create .XX places I use Code: var valueY=Math.round(valueX*100)/100; That way if valueX=15.6898 it would give valueY=15.69. but the problem arises when I want it valueX=15.6 to display valueY=15.60 I did some research and people said to use .toFixed(2) but i can't get it to add in the zero if it isn't already there. Any help I would be very helpful. This script is for car loan payments. I need a R simbol only before the monthly payment and only two figures after the decimal point. Can somebody pse help me with this. Thank you in advance. Kees Meyer (keesmarcha) <script language="JavaScript"> <!-- function showpay() { if ((document.calc.loan.value == null || document.calc.loan.value.length == 0) || (document.calc.months.value == null || document.calc.months.value.length == 0) || (document.calc.rate.value == null || document.calc.rate.value.length == 0)) { document.calc.pay.value = "Incomplete data"; } else { var princ = document.calc.loan.value; var term = document.calc.months.value; var intr = document.calc.rate.value / 1200; document.calc.pay.value = princ * intr / (1 - (Math.pow(1/(1 + intr), term))); } // payment = principle * monthly interest/(1 - (1/(1+MonthlyInterest)*Months)) } // --> </script> The results of this loan payment calculator are for comparison purposes only. They will be a close approximation of actual loan repayments if available at the terms entered, from a financial institution. This is being provided for you to plan your next loan application. To use, enter values for the Loan Amount, Number of Months for Loan, and the Interest Rate (e.g. 7.25), and click the Calculate button. Clicking the Reset button will clear entered values. <p> <center> <form name=calc method=POST> <table width=60% border=0> <tr><th bgcolor="#aaaaaa" width=50%><font color=blue>Description</font></th> <th bgcolor="#aaaaaa" width=50%><font color=blue>Data Entry</font></th></tr> <tr><td bgcolor="#eeeee">Loan Amount</td><td bgcolor="#aaeeaa" align=right><input type=text name=loan size=10></td></tr> <tr><td bgcolor="#eeeee">Loan Length in Months</td><td bgcolor="#aaeeaa" align=right><input type=text name=months size=10></td></tr> <tr><td bgcolor="#eeeee">Interest Rate</td><td bgcolor="#aaeeaa" align=right><input type=text name=rate size=10></td></tr> <tr><td bgcolor="#eeeee">Monthly Payment</td><td bgcolor="#eeaaaa" align=right><em>Calculated</em> <input type=text name=pay size=10></td></tr> <tr><td bgcolor="#aaeeaa"align=center><input type=button onClick='showpay()' value=Calculate></td><td bgcolor="#eeeeaa" align=center><input type=reset value=Reset></td></tr> </table> </form> <font size=1>Enter only numeric values (no commas), using decimal points where needed.<br> Non-numeric values will cause errors.</font> </center> <p align="center"><font face="arial" size="-2">This free script provided by</font><br> <font face="arial, helvetica" size="-2"><a href="http://javascriptkit.com">JavaScript Kit</a></font></p> I have a mortgage calc that is adding an extra decimal place to my interest rate. To see this in action go to: http://www.keithknowles.com/elmtree/mortgagecalc2.htm Change the interest rate to 7.5 Click Calculate Payment Click Create Amortization Chart On the following screen you'll see a recap of your data and the interest rate will now say 7.55. Same thing happens if you enter 6.2. Next screen shows 6.22/ I've attached the html and js files in a zip. Any help is greatly appreciated. Thanks. Hello all, How to set decimal point in javascript ? e.g. var num1=23.12345; I want output as 23.12 How can i do this ? Please, guide me. Thanks |