将两个整数相除时如何获得浮点值?(PHP)

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

How do I get a float value when dividing two integers? (PHP)

phpfloatingdivide

提问by user1869257

Hi I am trying to divide two integers ex: 12/13 but I always get a whole integer 1 not a decimal number.

嗨,我正在尝试将两个整数相除,例如:12/13,但我总是得到一个整数 1 而不是十进制数。

I tried type casting the values to float before hand with no success.

我尝试先将值强制转换为浮动,但没有成功。

Basically all I want is a decimal result like: 0.923...

基本上我想要的只是一个小数结果,如:0.923 ...

$x = 12;
$y = 13;
echo $value = $x / $y; //Would like to see 0.923 not 1

采纳答案by CS?

Under normal circumstances your code should return the floating value 0.923076...

在正常情况下,您的代码应该返回浮点值0.923076......

The reason you get a rounded integer might be because you have your ini settingfor "precision"set to 0, to fix this either edit your php.inior use ini_set("precision", 3);in your code before the calculation.

您获得四舍五入整数的原因可能是因为您将ini settingfor"precision"设置为0,要解决此问题,请在计算前编辑php.iniini_set("precision", 3);在代码中使用。

Another way to workaround this is to use BCmath:

解决此问题的另一种方法是使用BCmath

echo $value=bcdiv($a, $b, 3);


And yet another way without using any extension is to use a little math trick by multiplying the value you want to divide by 1000to get 3 decimals.
This way you'll divide 12000by 13and the whole part will be 923, then since you multiplied by 1e3 insert a comma/dot before the last most 3 places.

另一种不使用任何扩展的方法是使用一个小数学技巧,通过乘以您想要除以的值1000来得到3 decimals.
这样,你会除以12000通过13与整体的一部分会923,然后因为你之前的最后一次最多3位乘以1E3插入逗号/点。

function divideFloat($a, $b, $precision=3) {
    $a*=pow(10, $precision);
    $result=(int)($a / $b);
    if (strlen($result)==$precision) return '0.' . $result;
    else return preg_replace('/(\d{' . $precision . '})$/', '.', $result);
}

echo divideFloat($a, $b); // 0.923

echo divideFloat($a, $b); // 0.923

回答by Raffaello

echo $value = $x / (float) $y;

if you cast the variable $yas float the interpreter use the floating point division instead of integer division.

如果将变量转换$y为浮点数,则解释器使用浮点除法而不是整数除法。

because it's default asumption to use integer division on two integer variables.

因为默认假设对两个整数变量使用整数除法。

It was different if you used $y = 13.0(a float variable as denominator): The results is always a float number

如果您使用 $y = 13.0(作为分母的浮点变量)则不同:结果始终是浮点数

回答by felix021

All other answers are NOT RIGHT, because PHP's division will always return float values, as is stated clearly in official manual PHP: Arithmetic Operators, except for cases when two operands are both integers which can be evenly divided.

所有其他答案都不正确,因为 PHP 的除法将始终返回浮点值,正如官方手册PHP: Arithmetic Operators 中明确说明的那样,除非两个操作数都是可以被均分的整数。

In fact, the question is wrong: the code should produce 0.923..., as was expected from the questioner.

事实上,问题是错误的:代码应该产生 0.923...,正如提问者所期望的那样。

Sarcastically, the voted-down answer (came from @BulletProof47) is the only other one which is just NOT WRONG (but also meaningless). Who knows what he was thinking, but I bet everybody knows why it was voted down :D

讽刺的是,被否决的答案(来自@BulletProof47)是唯一一个没有错误(但也毫无意义)的答案。谁知道他在想什么,但我打赌每个人都知道为什么它被否决了:D

In case who is interested, the underlying function which does division in php is div_function, located in Zend/zend_operators.c, shown below:

如果有兴趣的话,php 中做除法的底层函数是div_function,位于 中Zend/zend_operators.c,如下图所示:

ZEND_API int div_function(zval *result, zval *op1, zval *op2 TSRMLS_DC) /* {{{ */
{
    zval op1_copy, op2_copy;
    int converted = 0;

    while (1) {
        switch (TYPE_PAIR(Z_TYPE_P(op1), Z_TYPE_P(op2))) {
            case TYPE_PAIR(IS_LONG, IS_LONG):
                if (Z_LVAL_P(op2) == 0) {
                    zend_error(E_WARNING, "Division by zero");
                    ZVAL_BOOL(result, 0);
                    return FAILURE;         /* division by zero */
                } else if (Z_LVAL_P(op2) == -1 && Z_LVAL_P(op1) == LONG_MIN) {
                    /* Prevent overflow error/crash */
                    ZVAL_DOUBLE(result, (double) LONG_MIN / -1);
                    return SUCCESS;
                }
                if (Z_LVAL_P(op1) % Z_LVAL_P(op2) == 0) { /* integer */
                    ZVAL_LONG(result, Z_LVAL_P(op1) / Z_LVAL_P(op2));
                } else {
                    ZVAL_DOUBLE(result, ((double) Z_LVAL_P(op1)) / Z_LVAL_P(op2));
                }
                return SUCCESS;
    ...

回答by BulletProof47

Just use $value = (float)($x/$y); //Result will in float.

只需使用 $value = (float)($x/$y); //结果会浮动。

Cheers!

干杯!