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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7037926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:22:58  来源:igfitidea点击:

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

javascriptjquerymath

提问by totallyNotLizards

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.

我还需要能够在 PHP 中进行完全相同的计算,但是如果有人可以帮助我解决数学问题,我可以移植任何需要自己翻译的内容。

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.

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

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.

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

回答by Digital Plane

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

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

回答by steven mcdowell

You can use the modulus to find the remainder after a division and then if the remainder is equal to zero then it's a multiple.

您可以使用模数在除法后找到余数,然后如果余数等于零,则它是倍数。

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

If the numbers your using could be to 2dp, the modulus should still work, if not, multiply both by 100 first then carry out the above check.

如果您使用的数字可能是 2dp,则模数应该仍然有效,如果不是,请先将两者乘以 100,然后执行上述检查。

回答by Peter Kelly

In javascript there is the remainder operator (similar to most languages with a c-like syntax).

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

Let x = length and y = price and z = product of x*y

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

var remainder = (z % x) / 100;

if (remainder === 0) {
   // z is a multiple of x
}

To get the closest x multiple to your result z you could round the result up (or down) using ceil or floor functions in the Math library.

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

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

Then round to two decimal places

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

Math.round(a / 100) * 100;

回答by Adam Leggett

This avoids JavaScript precision issues.

这避免了 JavaScript 精度问题。

function isMultiple(x, y) {
  return Math.round(x / y) / (1 / y) === x;
}

console.log(isMultiple(2.03, .01))
console.log(isMultiple(2.034, .01))
console.log(isMultiple(.03, .01))
console.log(isMultiple(240, 20))
console.log(isMultiple(240, 21))
console.log(isMultiple(1, 1))

回答by Udo G

Not sure if I really understood the task as it seems quite simple to me, but have a look at this PHP code:

不确定我是否真的理解这个任务,因为它对我来说似乎很简单,但看看这个 PHP 代码:

// --- input ---
$pattern = 12.34;
$input = 24.68;
$precision = 2; // number of decimals

// --- calculation ---

// switch to "fixed point":
$base = pow(10, $precision);
$pattern = round($pattern * $base);
$input = round($input * $base);

if ($input % $pattern) {
  // not an exact multiple
  $input = ceil($input / $pattern) * $pattern;
} else {
  // it is an exact multiple
}

// back to normal precision:
$pattern /= $base;
$input /= $base;

This can be easily translated to JavaScript.

这可以很容易地转换为 JavaScript。

$inputwill be the next closest multiple of the pattern. If you just need that and don't need to know if it actually was a multiple you could also simply do something like this:

$input将是模式的下一个最接近的倍数。如果您只需要它并且不需要知道它是否实际上是倍数,您也可以简单地执行以下操作:

$input = ceil($input * 100 / $pattern) * $pattern / 100;

回答by vellotis

//roundDown to 2 decimal places function
function r2(n) {
   return Math.floor(n*100)/100; 
}

neededLength = 4.55;
price = 4.63;
patternLength = 1.6;

// price despite the length of the pattern
priceSum = r2(neededLength * price);

// calculate how many pattern lengths there must be to fit into needed length
patternLengths = Math.floor((neededLength+patternLength)/patternLength);
// calculate price for pattern lengths
priceByPatternSum = r2((patternLengths * patternLength) * price );