Debt Consolidation - Find jobs - Property in Brazil - Web Directory - Novated lease

PDA

View Full Version : Function interaction - calculate volume and round


black_pigeon
Apr 23rd 2009, 6:02 pm
I'm a js noob trying to piece together two functions and I can't seem to make it work. I want to calculate the volume of form inputs and round to two decimal places. Here's what I'm trying:

VOLUME:
function Rec(form)
{form.an4.value = form.length4.value * form.width4.value * (form.height4.value/12) * .037}

ROUNDING:
function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
document.roundform.this.form.value = newnumber; // Output the result to the form field (change for your purposes)

FORM:
<p>length in feet <input type="text" name="length4"></p>
<p>width in feet <input type="text" name="width4"></p>
<p>depth in inches <input type="text" name="height4"></p>
<p><input type="button" class="submit" onClick="Rec(this.form)" value="Find Volume"></p>
<p><input type="text" name="an4"> <strong>CUBIC YARDS</strong></p>

The volume function works, but I'm not sure how to incorporate the rounding. I have two other volume calculations on this page in the same form, so I thought I needed to call the rounding from each volume function.

When you reply, speak slowly and with lots of arm waving - I might get what you're talking about. Thanks!

FilmFiddler
Apr 24th 2009, 5:37 pm
If you use the 'return' keyword in the last line of the roundNumber function, you can then just call upon the roundNumber function from any other function you like. So it can be called from the Rec() function as shown - that longish expression which calculates the volume can represent the rnum parameter in the function call.



<script type="text/javascript">
// VOLUME:
function Rec(form) {
form.an4.value = roundNumber(form.length4.value * form.width4.value * (form.height4.value/12) * .037, 2);
}

// ROUNDING:
function roundNumber(rnum, rlength) {
// Arguments: number to round, number of decimal places
return Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
}
</script>

black_pigeon
Apr 25th 2009, 7:24 pm
You are my hero! I mean seriously, this was driving me crazy and I spent way too much time trying to figure this out. Funny thing is that it didn't work when I first tried it, cause I had left a curly brace out in the ether. I just saw it about 10 minutes ago, and DADADUNDAH! It works.

I should probably learn javascript one of these days.