java script rounding to nearest 10
Copy link to clipboard
Copied
I have a form that needs to multiply two fields and then raound the answer to the nearest ten.
Below is what I have, can someone please tell me what I am missing
function DoubleRound(nDec, nValue) {
// Rounding function - round nValue to nDec decimal places
// use a double round to eliminate rounding error or Math.round
var nRound = Math.round(nValue / Math.pow(10, -nDec + 1)) * Math.pow(10, -nDec + 1)
return Math.round(nValue / Math.pow(10, -nDec)) * Math.pow(10, -nDec);
}
var u1= this.getField("TAXABLEVALUEOTHERPROPERTY").value;
var a1 = this.getField("RATIOOTHERPROPERTY").value;
event.value = ""; // default result if no divisor
if(Number(TAXABLEVALUEOTHERPROPERTY) != 0) {
// divisor not zero
var nResult = TAXABLEVALUEOTHERPROPERTY * RATIOOTHERPROPERTY; // compute division
nResult = DoubleRound(-1, nResult); // round to nearest 10
}
Copy link to clipboard
Copied
I wrote a generic function that does it:
// mode 0 = round v to nearest multiple of x, 1 = round down, 2 = round up
function roundToNearestX(v, x, mode) {
var mod = v%x;
if ((mod>=(x/2) && mode==0) || mode==2) return v+(x-mod);
if ((mod<(x/2) && mode==0) || mode==1) return v-mod;
}
For example: Calling roundToNearestX(16, 10, 0) will return 20.

