Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

jquery - javascript how to tell if one number is a multiple of another

I'm building a fairly calculation-heavy cart for a fabric store and have found myself needing to do a calculation on user inputted length * the baseprice per metre, but then checking the result to see if it is a multiple of the pattern length. If it is not a multiple, I need to find the closest multiple of the pattern length and change the result to that.

I need to also be able to do exactly the same calculation in PHP, but if anyone can help me out with the maths I can port anything that needs to be translated myself.

I am using jQuery 1.6.2 and already have the first part of the calculation done, I just need to check the result of (metres*price) against the pattern length.

Any help greatly appreciated

EDIT: These calculations all involve 2 decimal places for both the price and the pattern length. User inputted length may also contain decimals.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Ex.

//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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...