javascript如何判断一个数字是否是另一个数字的倍数

tot*_*rds 22 javascript math jquery

我正在为一家面料商店建造一个计算量很大的购物车,并且发现自己需要对用户输入的长度*每米的基本价格进行计算,然后检查结果以查看它是否是模式长度的倍数.如果它不是倍数,我需要找到最接近的模式长度倍数并将结果更改为.

我还需要能够在PHP中完成相同的计算,但如果有人可以帮我解决数学问题,我可以移植任何需要自己翻译的东西.

我正在使用jQuery 1.6.2并且已经完成了计算的第一部分,我只需要根据模式长度检查(米*价格)的结果.

任何帮助非常感谢

编辑:这些计算都涉及价格和模式长度的2位小数.用户输入的长度也可以包含小数.

Dig*_*ane 29

%在Javascript和PHP中使用(模数)运算符,它返回a除以bin 时的余数a % b.当a为倍数时,余数将为零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
Run Code Online (Sandbox Code Playgroud)


小智 24

您可以使用模数来找到除法后的余数,然后如果余数等于零,则它是一个倍数.

//x and y are both integers
var remainder = x % y;
if (remainder == 0){
//x is a multiple of y
} else {
//x is not a multiple of y
}
Run Code Online (Sandbox Code Playgroud)

如果您使用可能是2DP数字,模量应该仍然工作,如果没有,用100乘以首既然后再进行上述检查.

  • 只记得对数字进行舍入,这样就不会出现任何浮点问题,例如http://stackoverflow.com/questions/3966484/floating-point-numbers-and-javascript-modulus-operator (6认同)

Ada*_*ett 7

这避免了 JavaScript 精度问题(如果您的因子y少于 5 位小数)。

function isMultiple(x, y) {
    return Math.round(x / y) / (1 / y) === x;
}
Run Code Online (Sandbox Code Playgroud)

对于非常小的因子<= 1e-5,上述算法将失败。以下是一个解决方案,适用于所有将 <=Number.MAX_SAFE_INTEGER删除小数点的值,即最多 16 位的大多数值和最多 15 位的所有值,即大多数非科学值。

如果您正在处理科学价值,请使用big.js

function isMultiple(x, y) {
    return Math.round(x / y) / (1 / y) === x;
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*lly 5

在 javascript 中有余数运算符(类似于大多数具有类似 c 语法的语言)。

设 x = 长度,y = 价格,z = x*y 的乘积

var remainder = (z % x) / 100;

if (remainder === 0) {
   // z is a multiple of x
}
Run Code Online (Sandbox Code Playgroud)

要获得与结果 z 最接近的 x 倍数,您可以使用数学库中的 ceil 或 floor 函数将结果向上(或向下)四舍五入。

if (r >= x / 2) {
    a = Math.ceil(z/x)*x;
}
else {
    a = Math.floor(z/x)*x;
}
Run Code Online (Sandbox Code Playgroud)

然后四舍五入到小数点后两位

Math.round(a / 100) * 100;
Run Code Online (Sandbox Code Playgroud)