javascript如何判断一个数字是否是另一个数字的倍数
我正在为一家面料商店建造一个计算量很大的购物车,并且发现自己需要对用户输入的长度*每米的基本价格进行计算,然后检查结果以查看它是否为图案长度。如果它不是倍数,我需要找到模式长度的最接近的倍数并将结果更改为。
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.
我还需要能够完全执行PHP中的相同计算,但是如果有人可以帮我解决数学问题,我可以移植任何需要自己翻译的东西。
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.
我正在使用jQuery 1.6.2并已经完成计算的第一部分,我只需要根据模式长度检查(米*价格)的结果。
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.
任何帮助非常感谢
编辑:这些计算都涉及价格和模式长度的2位小数。用户输入的长度也可能包含小数。
These calculations all involve 2 decimal places for both the price and the pattern length. User inputted length may also contain decimals.
使用%
( Javascript和PHP中的模数运算符,当 a
在 b
时返回余数> a%b 。当 a
是 b
的倍数时,余数将为零。
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