浮点到字符串部分工作,为什么(字符串)在PHP中将0.999999999999999舍入为1? [重复]

问题描述 投票:-1回答:1

这个问题在这里已有答案:

这个问题最好是作为一个代码块。基本上我需要知道为什么每当将$ float2转换为带有(string)的字符串时$ float2被舍入为1,并且还需要一种方法来解决这个问题。我能够将其他花车投射到一个字符串而没有任何问题,但是这种情况发生了四舍五入是一个令人头疼的问题。

   $float1 = 0.99999999999999;
   $float2 = 0.999999999999999;
   $float3 = 0.00000000000001;
   $float4 = 0.000000000000001;
   echo $str1 = float_to_string($float1);
   echo ' type: '.gettype($str1)."\n"; //Echos:  0.99999999999999 type: string


   echo $str2 = float_to_string($float2);
   echo ' type: '.gettype($str2)."\n"; //Echos: 1 type: string

   echo $str3 = float_to_string($float3);
   echo ' type: '.gettype($str3)."\n"; //Echos: 0.00000000000001 type: string

   echo $str4 = float_to_string($float4);
   echo ' type: '.gettype($str4)."\n"; //Echos: 0.000000000000001 type: string


   if ($float2 != 1)
   {
      echo "No rounding done in if clause so this means that (string) is doing the rounding.\n";
   }

function float_to_string($float)
{
   $parts = explode('E', $float);
   if(count($parts) === 2)
   {
      $exp = abs(end($parts)) + strlen($parts[0]);
      $decimal = number_format($float, $exp);  //This converts it to a string
      echo "Returning with number_format\n";
      return rtrim($decimal, '.0');
   }
   else
   {
      echo "Returning without number_format\n";
      return (string)$float; //Why is this rounding 0.999999999999999 to 1?!  I thought only number_format did rounding.
   }
}
php string double
1个回答
2
投票

浮点的大小取决于平台,但最大值约为1.8e308,精度约为14位十进制数是一个常见值(64位IEEE格式)。

https://www.php.net/manual/en/language.types.float.php

PHP的精度是14位数,第一个是14位数,第二个是15位,超过了精度,因此它被舍入。

另外我相信你可以将ini的精度设置为超过14位,但由于浮点数的工作方式,你的数学运算可能最终不准确。

© www.soinside.com 2019 - 2024. All rights reserved.