JavaScript - Input Force Decimal Places
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. Similar TutorialsGood 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!!! 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 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 function below will output price value in text field based on drop-menu option. It's working but I want it's always show value in 2 decimal point for variable 'price'. Can anyone help me with this problem? function findPrice() { if (document.getElementById("region").value == "blank") { var price = document.getElementById("price"); price.value = "<?php echo 'Choose your region to get the price'; ?>"; } if (document.getElementById("region").value == "Peninsular Malaysia") { var price = document.getElementById("price"); price.value= '<?php echo $PM_Price; ?>'; } if (document.getElementById("region").value == "Sabah/Labuan") { var price = document.getElementById("price"); price.value = '<?php echo $SL_Price; ?>'; } if (document.getElementById("region").value == "Sarawak") { var price = document.getElementById("price"); price.value = '<?php echo $SR_Price; ?>'; } } Hi, I have a text input that will default to "0.00". However, entries can be for a length of 15 and must include a decimal with 2 positions (hundredths)... How can I force this and prevent 14/15 positions with no decimal being used or a decimal mis placed giving more positions beyond 2 to the right of the decimal? Your response is appreciated -Ron 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 ^^ 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 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 , 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? 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 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. Hi All, Im currently working on a bidding application built within ASP.Net and i have found this javascript snippet to only allow numeric values in the desired <asp:textbox> which is working fine, but i want to allow the user to add a decimal place. For example, say the bid is 1.50 they should be allowed to enter 1.51 but as i cant imput (.) i end up putting in 151 heres the snippet it may be a slight modification but im new to javascript so any help of knowledge will be highly appreciated Code: function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } thanks in advance 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> Hi, Dreamweaver generated the javascript for an onBlur validation for an input textbox. Is it possible to change this code so that I do not have a range but, instead, specific numbers that must be input by the user? I want to ensure that the users input integers and only the following decimals: .25; .5, and .75. [function MM_validateForm() { //v4.0 if (document.getElementById){ var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]); if (val) { nm=val.name; if ((val=val.value)!="") { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; } } if (errors) alert('The following error occurred:\n'+errors); document.MM_returnValue = (errors == ''); } } </script>] John I am having an issue with converting my decimal to a percentage... any suggestions? Thanks - it's probably an easy solution, but I am lost below is my code (cost * .06) is where the issue is - Thanks! var cost = prompt("What is the cost of your purchase?", "") document.write("Return Value: "+cost,("<br />")); var salestax = cost * .06 document.write("Return Value: "+salestax,("<br />")); var total = cost + salestax document.write(cost + salestax); I'm trying to write a pi calculator that shows a comparison of the calculated value to the actual value. It works, but the output of the comparison shows only the first two decimal spots, followed by two 9s. Why is it showing two 9s and how can I make it more precise? Code: <head> <title> Pi Calculator </title> <script language="JavaScript"> function calcpi(digitsn) { p = 1; s = 0; for (c = 3; c < digitsn; c += 2) { if (s == 0) { p -= 1/c; s = 1; } else { p += 1/c; s = 0; } } p *= 4; return p; } function hid(input) { //Highlight Incorrect Digits pi = "3.14159265358979323846".split(''); input = input.toString().split(''); result = ""; for (c = 0; c < input.length; c++) { if (input[c] != pi[c]) { //result += "; " + input[c] + "!=" + pi[c]; result += "<span style='background-color:red'>" + input[c] + "</span>"; } else { result += input[c]; } } return result; } </script> </head> <body> Repeat algorithm x many times:<br/> <input type="text" value="10000" id="digitsx"/><br/> <input type="button" onClick="document.getElementById('answer').value=calcpi(parseInt(document.getElementById('digitsx').value)).toString()" value="Calculate"/><br/> Result:<br/> <input type="text" readonly id="answer"/><br/> Correct value:<br/> <input type="text" readonly value="3.14159265358979323846"/><br/> <input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid('3.1499')"/> <div id="comparison"/> </body> 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 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. I am trouble in comparing decimal number. var1 = 0.25 var2 = 0.50 if (var1<var2) { alert("Value is less than minimum") } else { return true; } How can I make it work. Thanks for help in advance |