In this example any floating point decimal number entered in the first text box will be rounded to the number of decimal places specified in the second text box of the form.
The result is written to the third text box. The start values are taken from the rndfunction form and passed to the supplyno function which passes those values to the rndresult function.
The rndresult function returns the number to the calling function rounded to the specified decimal place. Writing the code in this manner makes it possible for the rounding function used by be multiple functions within the document as long as they are able to supply the correct arguements in the correct order.
The order of the arguements in function declaration must be the same as the function call. Any differences in variable names between functions do not matter because they are local to that function.
// Function purpose: supply floating point decimal number and the number of digits to round down to.
//Values are passed on by form 'rndfunction()
//Call rounding function rndresult()
rawresult = rawno.value;
rnddigits= Math.floor(rnddigits);// Make sure that rounding digit is an integer.
realresult = rndresult(rawresult,rnddigits);
// Write result to textbox(result) in the form (rndfunction)
document.rndfunction.result.value = realresult;
// order of arguements in function declaration must be the same as the function call.
// in supplyno() - realresult = rndresult(rawresult,rnddigits);
// values are passed based on their order.
//Differences in variable names between functions do not matter because they are local to that function only.
//round results and return value
var realresult = rawresult;
var decimalpl = rnddigits;
//take rounding digits and make decimalpl = 10 to the (rounding digits) power
var decimalpl = (Math.pow(10,decimalpl));
// Math.round will only round to nearest integer multiply by 10 to the number of decimal places.
//Round the result and divide by 10 to the number of decimal places.
realresult = (Math.round(realresult *decimalpl))/decimalpl;
var roundedresult = parseFloat(realresult); // Use parseFloat to make sure that number is delivered
return(roundedresult) // return rounded number to calling function.