在PHP中使用(int)时值不准确


Inaccurate value in using (int) in PHP

我在这个代码块上有一个问题

    $Fee = 275.21;
    $feeAmount1 = (int) ( floatval ( $Fee ) * 100 );
    echo $feeAmount1 . '<br />';

我在结果上得到一个这个。

27520

我需要将其转换为int但我在(int)函数中得到了不准确的值

希望有人能帮我一下。

听起来像是浮点错误。

例如,对于方程275.21 * 100, FPU可能会给出27520.999...。(它很接近,对吧),然后在转换为int型时,小数被条纹化。

可以先四舍五入再转换为整型:

$feeAmount1 = (int) ( round( $Fee * 100) );

这是php的一个已知行为。

一个浮点数,比如27521,实际上是27520.999999999999991。当您强制转换它时,您将截断小数部分。

因此使用round, floor或ceil方法将其四舍五入到最接近的整数:

http://php.net/manual/en/function.round.php

http://php.net/manual/en/function.ceil.php

http://php.net/manual/en/function.floor.php

修改代码:

  $Fee = 275.21;
  echo $FeeWOD = round($Fee * 100); //Should be 27521,00
  echo "<br>";
  echo $feeAmount1 = (float) $FeeWOD;
  echo "<br>";
  echo intval ($feeAmount1);
  echo "<br>";

不能从浮点数转换为整数。你需要先四舍五入。

为什么是反对票?

当从浮点数转换为整数时,数字将向零四舍五入。

阅读此页。http://php.net/manual/en/language.types.integer.php

警告

永远不要将未知分数强制转换为整数,因为这有时会导致意想不到的结果。

<?php
   echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>

参见float精度的警告。

http://php.net/manual/en/language.types.float.php#warn.float-precision

如果你的值总是带有2个小数点,你可以使用结果而不将其类型转换为int。你能提供更多关于"为什么需要整数值"的细节吗?.

欢呼