用PHP进行计算

用PHP进行计算,php,math,Php,Math,考虑下面给出的大型计算 echo 999999*999999999; 这将返回9.9999899e+14 有没有办法得到整数而不是指数形式 请帮忙。提前感谢。不,PHP将向上取整,超过24亿值的整数将浮起,如果您有64位系统,PHP可能会走得更远,但您所要求的是根本不可能的 整数的大小取决于平台,尽管是最大值 大约20亿是通常的值(即32位有符号)。PHP 不支持无符号整数。可以确定整数大小 使用常量PHP_INT_SIZE,最大值使用常量 自PHP4.4.0和PHP5.0.5以来的PHP_

考虑下面给出的大型计算

echo  999999*999999999;
这将返回
9.9999899e+14

有没有办法得到整数而不是指数形式


请帮忙。提前感谢。

不,PHP将向上取整,超过24亿值的整数将浮起,如果您有64位系统,PHP可能会走得更远,但您所要求的是根本不可能的

整数的大小取决于平台,尽管是最大值 大约20亿是通常的值(即32位有符号)。PHP 不支持无符号整数。可以确定整数大小 使用常量PHP_INT_SIZE,最大值使用常量 自PHP4.4.0和PHP5.0.5以来的PHP_INT_MAX


代替echo,这样做:
使用sprintf

$a = 999999*999999999;
$myvar = sprintf('%.0f', $a);

使用GNU多精度扩展:


我想自己编写,但通过查看php文档,我发现了一个现成的函数。 它像GMP或BCMath一样将整数作为字符串。这样,您的尺寸就不受限制了

此处提供以下功能:


顺便说一句,这不是PHP独有的问题。即使强制显示非指数形式,浮点值也总是容易受到舍入错误的影响
<?php 
$no = 999999*999999999;
echo sprintf('%.0f', $no);
?>
function Mul($Num1='0',$Num2='0') {
  // check if they're both plain numbers
  if(!preg_match("/^\d+$/",$Num1)||!preg_match("/^\d+$/",$Num2)) return(0);

  // remove zeroes from beginning of numbers
  for($i=0;$i<strlen($Num1);$i++) if(@$Num1{$i}!='0') {$Num1=substr($Num1,$i);break;}
  for($i=0;$i<strlen($Num2);$i++) if(@$Num2{$i}!='0') {$Num2=substr($Num2,$i);break;}

  // get both number lengths
  $Len1=strlen($Num1);
  $Len2=strlen($Num2);

  // $Rema is for storing the calculated numbers and $Rema2 is for carrying the remainders
  $Rema=$Rema2=array();

  // we start by making a $Len1 by $Len2 table (array)
  for($y=$i=0;$y<$Len1;$y++)
    for($x=0;$x<$Len2;$x++)
      // we use the classic lattice method for calculating the multiplication..
      // this will multiply each number in $Num1 with each number in $Num2 and store it accordingly
      @$Rema[$i++%$Len2].=sprintf('%02d',(int)$Num1{$y}*(int)$Num2{$x});

  // cycle through each stored number
  for($y=0;$y<$Len2;$y++)
    for($x=0;$x<$Len1*2;$x++)
      // add up the numbers in the diagonal fashion the lattice method uses
      @$Rema2[Floor(($x-1)/2)+1+$y]+=(int)$Rema[$y]{$x};

  // reverse the results around
  $Rema2=array_reverse($Rema2);

  // cycle through all the results again
  for($i=0;$i<count($Rema2);$i++) {
    // reverse this item, split, keep the first digit, spread the other digits down the array
    $Rema3=str_split(strrev($Rema2[$i]));
    for($o=0;$o<count($Rema3);$o++)
      if($o==0) @$Rema2[$i+$o]=$Rema3[$o];
      else @$Rema2[$i+$o]+=$Rema3[$o];
  }
  // implode $Rema2 so it's a string and reverse it, this is the result!
  $Rema2=strrev(implode($Rema2));

  // just to make sure, we delete the zeros from the beginning of the result and return
  while(strlen($Rema2)>1&&$Rema2{0}=='0') $Rema2=substr($Rema2,1);

  return($Rema2);
}

echo Mul('999999', '999999999');
$a = 99999999*99999999999;
echo sprintf('%.0f', $a);
echo Mul('99999999', '99999999999');