应对32位PHP的大型INT
-
12-12-2019 - |
题
我有一个用于计算LUHN校验和的类。它将整数作为输入,返回true或false以指示有效性或其他方式,如果给出不适当的数据类型作为输入,则会抛出异常。
代码如下(完整源位于 github ):
class Luhn extends abstr\Prop implements iface\Prop
{
/**
* Test that the given data passes a Luhn check.
*
* @return bool True if the data passes the Luhn check
* @throws \InvalidArgumentException
* @see http://en.wikipedia.org/wiki/Luhn_algorithm
*/
public function isValid ()
{
$data = $this -> getData ();
$valid = false;
switch (gettype ($data))
{
case 'NULL' :
$valid = true;
break;
case 'integer' :
// Get the sequence of digits that make up the number under test
$digits = array_reverse (array_map ('intval', str_split ((string) $data)));
// Walk the array, doubling the value of every second digit
for ($i = 0, $count = count ($digits); $i < $count; $i++)
{
if ($i % 2)
{
// Double the digit
if (($digits [$i] *= 2) > 9)
{
// Handle the case where the doubled digit is over 9
$digits [$i] -= 10;
$digits [] = 1;
}
}
}
// The Luhn is valid if the sum of the digits ends in a 0
$valid = ((array_sum ($digits) % 10) === 0);
break;
default :
// An attempt was made to apply the check to an invalid data type
throw new \InvalidArgumentException (__CLASS__ . ': This property cannot be applied to data of type ' . gettype ($data));
break;
}
return ($valid);
}
}
.
我还建立了一个完整的单元测试< / a>锻炼课程。
我以为我可以在午餐期间的一些业余时间(Windows 7,XAMPP,32位PHP 5.3)用于在这个类是一部分的项目上工作,但我跑进的第一件事是失败的测试。
解决方案
如果需要精度,则不应使用floats。
而是,特别是因为要使用整数(如果我理解正确),则可以尝试使用gmp*
函数: gmp - gnu多重精度
如果您无法使用该扩展,您可能会从中获取一些额外的想法
其他提示
如果需要精度,则不应使用floats。
而是,特别是因为要使用整数(如果我理解正确),您可以尝试使用bc*
函数: bcmath任意精度数学
不隶属于 StackOverflow