仅从使用 PHP 的除法中获取余数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3272964/
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-25 09:11:37  来源:igfitidea点击:

Get remainder only from a division using PHP

php

提问by X10nD

I am dividing 19/5where by I have used 19/5but I am unable to get the remainder only.

我正在除以19/5我使用过的地方,19/5但我无法获得其余部分。

How do I get it.

我怎么得到它。

Thanks Jean

谢谢让

采纳答案by Sadat

Please try it-

请尝试一下-

  $tempMod = (float)($x / $y);
  $tempMod = ($tempMod - (int)$tempMod)*$y;

回答by Mark Baker

echo 19 % 5;

should return 4, which is the remainder of 19/5 (3 rem 4) There is no need to use floor, because the result of a modulus operation will always be an integer value.

应该返回 4,即 19/5 (3 rem 4) 的余数 不需要使用 floor,因为模运算的结果将始终是整数值。

If you want the remainder when working with floating point values, then PHP also has the fmod() function:

如果在处理浮点值时需要余数,那么 PHP 也有 fmod() 函数:

echo fmod(19,5.5);

EDIT

编辑

If you want the remainder as a decimal:

如果您希望余数为小数:

either

任何一个

echo 19/5 - floor(19/5);

or

或者

echo (19 % 5) / 5

will both return 0.8

都将返回 0.8

回答by mattbasta

Depending on what language you're using, %may not be the modulus operator. I'll assume you're using PHP, in which case it is %.

根据您使用的语言,%可能不是模运算符。我假设您使用的是 PHP,在这种情况下它是%.

From what I can see, there is no need to use floor()with integer modulus, it will always return an integer. You can safely remove it.

从我所见,没有必要使用floor()整数模数,它总是会返回一个整数。您可以安全地删除它。

To me, it looks like it isn't the math that's giving you hell, it's the code around it. You'll need to post more code; the code you have listed is fine.

对我来说,看起来不是数学让你感到痛苦,而是围绕它的代码。您需要发布更多代码;您列出的代码很好。

Edit:

编辑:

You're not looking for the remainder, you're looking for the left over decimal value. It has no name.

您不是在寻找余数,而是在寻找剩余的十进制值。它没有名字。

$leftover = 19 / 5;
$leftover = $leftover - floor($leftover);

This should be what you're looking for.

这应该是你要找的。