Re: [DISCUSSION] Adding the "is_integer_safe()" function
| From: | Claude Pache | Date: | Mon, 28 Jul 2025 10:18:18 +0000 |
| Subject: | Re: [DISCUSSION] Adding the "is_integer_safe()" function | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-128251@lists.php.net to get a copy of this message | ||
> Le 26 juil. 2025 à 18:13, Alexandre Daubois <alex.daubois+php@gmail.com> a écrit :
>
>>
>> I'm not sure if accepting floats in the same function makes sense. If the question is
>> "can this value safely be stored in a float?" and you give it a float, then the answer is
>> surely "yes". You have no way of knowing if it _already_ lost precision during a previous
>> operation.
>>
>> Possibly there could be a separate function which asks "can this float value be safely
>> converted to an integer?", but that implies a different definition - it wouldn't make much
>> sense to answer "yes" for 3.5, or NaN.
>
> I think we can see this function more like "can this number be
> compared safely?", e.g.
var_dump(2**53 === (2**53)+1);
> returns true
> as these numbers are not in the safe interval. A name like
> is_safely_comparable() would fit better maybe.
This is not correct: 2**53 + 1 is perfectly “safe” (for 64-bit builds of PHP), see: https://3v4l.org/P939d
The specific notion of “safe integer” as introduced in JavaScript makes sense only for numbers
encoded using IEEE 754, which is what PHP uses for float. In PHP, there is a
specialised type for integers, so that the need of such a function is not clear, because every
integer encoded as int is “safe”. Or maybe you want something like
is_safe_integer_when_interpreted_as_float()?
Also, note that the particular Symfony example given at the beginning of this thread uses a function
that expects a string, not an int or a float. In that example, something like
is_numeric_value_producing_exact_integer_when_interpreted_as_float() could have been
useful, but this use case is very specialised.
—Claude