JavaScript - Correct Rounding Procedure
I have tried many ways to do this and have also searched the forum, no go. I was doing it manually doing this:
Code: Math.round((#)*100)/100 But no go, so I found this function here on the forum: Code: function roundNumber(num, dec) { var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); return result; } No go, it works yes, don't get me wrong. But I am working on a invoicing system and it needs to be exact. For instance with this number: Quote: 0.27470000001 It returns 0.27, when in reality it should return 0.28 because of the 7 changes the 4 to 5 and then 5 changes the 7 to 8. But it doesn't work. While reading some things I found while searching google I see that Math.round doesn't work 100% the way it should mathematically. So what options do I have left, I can't believe that a simple rounding calculationg that excel can do ha ha JS cannot. Similar Tutorialsis there a HTML or a java script code that will allow me to create a link on my page and this link will allow me to access a site (that requires my username and password) to be automatically logs me in and access the data. or is there a way to enter the username and password to the URL that would help me not to login... So I use Math.round to round my solution off to the nearest thousandth, but if I put in 6 for the number I am solving for it returns 1.333 When I multiply that by 3 it gives me 3.999 when I really want 4.0 Is there any way I can use fractions or something to get around this? My project: http://wdroom.com/factor.html Hello, I need to be able to get a number to 2dp without rounding e.g. 14.756 needs to be 14.75 I tried .toFixed(2) but this rounds. I thought of converting to a string and performing string functions but it seems like over kill if there is an easier way. thanks Code: num = 1.025; alert(num.toFixed(2)); // - comes out as 1.02 num = 0.025; alert(num.toFixed(2)); // comes out as 0.03; Why is this? I recently started trying to learn javascript and I decided to try an exercise I found somewhere. Basically it involves counting eggs into total, dozen, and gross. The problem is when I put in a number lower than a full dozen or gross it rounds up and says I have the full dozen intead of the fraction. Ex. I say I have 143 eggs, it says I have 12 dozen. Obviously I am 1 short. Apparently the method(I think that is what it is called?) rounds to the nearest number. Which methods? round either up or down? Here is the code... Code: <html> <head> <title></title> <script type="text/javascript"> function eggs(number) { var total=prompt("eggs",""); alert("You have "+total+" eggs."); var dozen=(total/12); alert("You have "+dozen+" dozen eggs."); var gross=(total/144); alert("You have "+gross+" gross eggs."); var fulldozen=(Math.round(dozen)); alert("You have "+fulldozen+" dozen eggs."); var fullgross=(Math.round(gross)); alert("You have "+fullgross+" gross eggs."); } </script> </head> <body> <form> <a href="javascript:eggs('number')"><input type="button" value="Eggs" name="Eggs" size="30"></a> </form> </body> </html> Thanks for reading. Edit: Also, it goes through the whole thing twice. It will prompt the first time, go through, then prompt again. It terminates after the second though. Code: function convertee(){ value = document.inputFormee.argument.value; if (isNaN(value)){ alert(value+' is not a valid entry'); return; } arg = (value/1.75975326); arg = (parseInt(arg*100)/100).toFixed(3); document.inputFormee.result.value = arg; } Any help much appreciated. Saz. Hello guys I am doing a simple calculation. Here is the code Code: dose=1 A = document.rhogam.bleed.value B = document.rhogam.volume.value dose= (A*B)/3 dose=Math.round(dose*10)/10; this works fine and gives me an answer rounded to the tenths spot. the next step i need to do is round up by one if the tenths spot is less than 4 or round up by 2 if the tenths is 5 plus example 3.3=4 3.6=5 The code issue I am having is how do I read the tenths place in my result so that I can act on it? Thanks Jeremy I am currently using a price calculator - although it's really not a calculator; I have to enter every price manually. Currently, it works in half inch increments. I need it to do two things that it doesn't do currently: 1) Allow the customer to enter a dimension in 1/4 inch increments (1/8 would be even better, but I'm not requesting a miracle) 2) Make the result automatically round up to the nearest 1/2 inch Page containing calculator External file: sizecalc.js Wizards - I have a challenge! I am writing a timecard app. The stipulatioin is all Hours fields can only be whole hours or half hour increments. For example, 1.0 is good, 1.5 is good, 1.2 is bad, 1.9 is bad. I would like to have the field automatically change a value of 1.9 to a value of 2.0 (perhaps onKeyUp). I would like to have the field automatically change a value of 3.2 to a value of 3.0. In a nutshell - only allow whole and half hour values. Otherwise round up OR round down. Thanks for any help you can provide. I am successfully using the Pengoworks plugin for calculations - absolutely priceless. If you think modifications can be made to it, plz let me know. 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 To Forum Thank you for being here. I have taken 2 calculators and edited them to get almost what i want. I need the final answer to round up to a whole number. The page is http://www.La-Dore.com/Goldleaf-Calculator.html The code i think you want to see is .... Code: <!-- end of script 1 begining of 2--> <SCRIPT LANGUAGE="JavaScript"> function perRound(num, precision) { var precision = 3; precision = parseInt(precision); var result1 = num * Math.pow(10, precision); var result2 = Math.round(result1); var result3 = result2 / Math.pow(10, precision); return zerosPad(result3, precision); } function zerosPad(rndVal, decPlaces) { var valStrg = rndVal.toString(); var decLoc = valStrg.indexOf("."); if (decLoc == -1) { decPartLen = 0; valStrg += decPlaces > 0 ? "." : ""; } else { decPartLen = valStrg.length - decLoc - 1; } var totalPad = decPlaces - decPartLen; if (totalPad > 0) { for (var cntrVal = 1; cntrVal <= totalPad; cntrVal++) valStrg += "0"; } return valStrg; } function clear_field(field) { if (field.value==field.defaultValue) { field.value='' } } //Division function doMath(form) { var firstnumber = 0; var secondnumber = 0; var tempvalue = 0; firstnumber = eval(form.firstnumber.value); //first number secondnumber = eval(form.secondnumber.value); //second number tempvalue = (firstnumber) / (secondnumber); form.calcresult.value = (tempvalue); //out } // --> </script> Hi there, To summarize my problem: For example: Sales : $ 5 (id=sales) Discount: 11% (id=disc) Total Discount: $ 0.55 (id=disc) Rounded Discount: $ 0.6 (1 decimal) (id=rounded) Net Sales: $ 4.40 (id=net_sales) document.getElementById("net_sales").value = sales - rounded.toFixed(1); Net Sales: $ <input id = "net_sales" type="Text" name="net_sales" size="4" value="<?php if (!empty($net_sales)) echo $net_sales; ?>"> I tried the above, it is working in the browser. However, it cannot be written into MYSQL (with PHP). What is wrong with my Javascript? Thanks. Can anyone tell me what I have done wrong here? I have the following html code Code: <div id='group1'> <tr class='time'> <td colspan='3' name='1262815200'></td> </tr> <tr> <td class='timeleft group1' name='1262815200' colspan='3'></td> </tr> <tr class='game'> <td><input type='radio' name='G1' value='NYJ'>NYJ</td> <td><input type='radio' name='G1' value='BUF'>BUF</td> <td><select name='G1P' class='points' tabindex = '1'></select></td> </tr> </div> and when I use the selector $('#group1 input) it does not select anything (namely the inputs in this code). But when I use the selector $('div input') it will select them (and more on the page which I don't want). Is anyone able to see what I have done wrong? I've tried everything I can think of in terms of testing, and I have narrowed it down to the selector. Thanks. How can I change the day when the user select a month? When they select Feb ->29 days, select May -> 31 days. Like what facebook does. Does anyone know why I am not getting an alert on an empty form INPUT value? Code: if (document.forms["form"]["targetname"].value == "" && document.forms["form"]["unknownname"] == false) { alert ("What ever"); return false; } document.forms["form"]["targetname"] is a form INPUT text document.forms["form"]["unknownname"] is a form INPUT checkbox I suspect the problem is due to 'false'.. but I can't figure out why. I found and am using the following script to add checkbox values to a textarea. Code: <script type="text/javascript"> function add_sub(el){ if (el.checked) el.form.elements['type'].value+=el.value; else{ var re=new RegExp('(.*)'+el.value+'(.*)$'); el.form.elements['type'].value=el.form.elements['type'].value.replace(re,'$1$2'); } } </script> </head> <body> <form name="form1" method=post> <textarea name="type" rows="5" cols="35" onclick="this.focus();this.select();"> </textarea><br> <input type="checkbox" name="bob" id="bob" value="<p>" onclick="add_sub(this);"><label for="bob"><p></label><br> <input type="checkbox" name="bob1" id="bob1" value="<span>" onclick="add_sub(this);"><label for="bob1"><span></label><br> <input type="checkbox" name="bob2" id="bob2" value="<div>" onclick="add_sub(this);"><label for="bob2"><div></label> That is working. However, I wanted to put carriage returns after each checkbox value added, so I added the + "\r\n" as follows: Code: <script type="text/javascript"> function add_sub(el){ if (el.checked) el.form.elements['type'].value+=el.value + "\r\n"; else{ var re=new RegExp('(.*)'+el.value+'(.*)$'); el.form.elements['type'].value=el.form.elements['type'].value.replace(re,'$1$2'); } } </script> That is working when adding the value, but removing the value when the checkbox is unchecked is not working. I know the regular expression, etc. needs to be updated to account for the carriage returns, but I have tried everything I can think of and cannot get it to work. Help correcting the code is appreciated. Which of these is the correct way to set the className attribute, or are they both okay? option 1: Code: var t = document.createElement("p"); t.className = "myclass"; option 2: Code: var t = document.createElement("p"); t.setAttribute("class","myclass"); Hello coding forum users, I am working on the only javascript chapter of my HTML textbook. It asks me to: Quote: replace the line <img id="sky" src="sky0.jpg" alt=""/> with a script element that writes the following HTML code: <img id='sky' src='mapNum.jpg' alt=' ' /> where mapNum is the value of the mapNum variable. so I try PHP Code: <script type="text/javascript" /> document.write("<img id='sky' src='mapNum.jpg' alt=' ' />") </script> after a few other attempts I search codingforums and find: PHP Code: document.write("<img id=\"sky\" src='sky"+mapNum+".jpg' alt='' />"); and PHP Code: document.write('<img id="sky" src="sky'+mapNum+'.jpg" alt="" />'); and these work perfectly fine but I don't understand why? my textbook only has one javascript chapter and its really small and vague, and my teacher hasn't answered my emails, so I would be grateful if anyone can tell my why my first code falls flat. Hi, I'm trying to figure out how to make this work and I'm stumped. I wrote this code: <script type=text/javascript> function firstfunction(); { if(document.form1.inputnumbers.value="55"); { document.form1.outputstate.value="this is a number"; } else if { document.form1.inputnumbers.value="never"; } { document.form1.outputstate.value="this is a number"; } else { document.form1.outputstate.value=""; } </script> <form name="form1" method="post"> <input type="text" id="inputnumbers" name="inputnumbers";> <input type="button"; value="Enter"; onclick="firstfunction()"><br><br> <textarea id="outputstate"; name="outputstate"; cols=60; rows=10; style="border:1"; readonly;> I'm trying to doing something really simple but I can't seem to make it work. I'm trying have the textarea display a certain message depending on if the first input box says a certain word or number. So like in the code, if the user types "55" or "never" in the first box, then the second box should say a certain message. Then I used the else statement so that if "55" or "never" is not entered, then the second box says nothing. If you can spot my error or suggest a different way of going about writing the code, it would be very much appreciated. Thank you. Good evening. I'm very new to this, but very excited that I've gotten this code so close. I am trying to get the computer to determine if a number is even or not. This is what I have: [CODE] <script type = "text/javascript"> <!-- var firstNumber; // first string entered by user var answer; // the division problem // read in first number from user as a string firstNumber = window.prompt("Enter an integer"); //how to get a remainder var answer = firstNumber / 2 if (answer > 1) { document.writeln(answer + ". This number is even."); } </script> The bottom part is the problem. I am able to code that if the answer is greater than one, then return the following text, however, I can't for the life of me figure how to say... if the remainder is zero. Thank you, |