当从字符串转换为int导致精度损失时,如何抛出异常


how can I throw an exception when casting from string to int caused precision loss?

是否有方法在从字符串转换为int之前或之后实际检查是否存在精度损失并引发异常?

$id = "21321312412435453453453454"
$numId = (int) $id;

这应该适用于您:

(刚刚使用php predefined constants进行比较)

$id = "21321312412435453453453454";
if($id > PHP_INT_MAX)
    echo "too big";
else
    echo "okay";

输出:

too big

编辑:

对于负数,你可以这样定义常数:

define('PHP_INT_MIN', ~PHP_INT_MAX); 

您甚至可以在手册中阅读有关PHP_INT_MAX的信息:http://php.net/manual/en/language.types.integer.php

还有一句话:

整数的大小取决于平台,尽管最大值约为20亿是通常的值(即32位符号)。64位平台通常具有大约9E18的最大值,但Windows除外,它总是32位PHP不支持无符号整数。整数大小可以使用常量PHP_INT_size来确定,最大值使用自PHP 4.4.0和PHP 5.0.5以来的常量PHP_INT_MAX来确定。

尝试将其强制转换回字符串并比较两者。