考虑下面给出的大计算
echo 999999*999999999;
这返回9.99998999E+14
有没有办法得到整数999998999000001
而不是指数形式?
请帮忙 。提前致谢。
而不是回声,请执行以下操作:use sprintf
$a = 999999*999999999;
$myvar = sprintf('%.0f', $a);
使用 GNU 多精度扩展:
不,PHP 会四舍五入,浮点数超过 24 亿的整数,如果你有 64 位系统 PHP 可能会更进一步,但你要问的是根本不可能的。
整数的大小取决于平台,尽管通常值约为 20 亿的最大值(即 32 位有符号)。PHP 不支持无符号整数。自 PHP 4.4.0 和 PHP 5.0.5 起,可以使用常量 PHP_INT_SIZE 确定整数大小,使用常量 PHP_INT_MAX 确定最大值。
<?php
$no = 999999*999999999;
echo sprintf('%.0f', $no);
?>
我想自己写,但是查看 php 文档我发现了一个现成的函数。它像 GMP 或 BCMath 那样将整数作为字符串。这样,您就不受大小的限制。
此处提供以下功能:http ://www.php.net/manual/en/function.bcmul.php
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');