Menu

Javascript How To Tell If One Number Is A Multiple Of Another

Use the % (modulus) operator in Javascript and PHP, which returns the remainder when a is divided by b in a % b. The remainder will be zero when a is a multiple of b.

 


 

//Javascript
var result = userLength * basePrice;     //Get result
if(result % patternLength){              //Check if there is a remainder
  var remainder = result % patternLength; //Get remainder
  if(remainder >= patternLength / 2)      //If the remainder is larger than half of patternLength, then go up to the next mulitple
    result += patternLength - remainder;
  else                                    //Else - subtract the remainder to go down
    result -= remainder;
}
result = Math.round(result * 100) / 100;  //Round to 2 decimal places

 

652
Search

Ads