Re: [DISCUSSION] Adding the "is_integer_safe()" function
| From: | Alexandre Daubois | Date: | Mon, 28 Jul 2025 13:00:52 +0000 |
| Subject: | Re: [DISCUSSION] Adding the "is_integer_safe()" function | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-128258@lists.php.net to get a copy of this message | ||
Le lun. 28 juil. 2025 à 12:14, Gina P. Banyard <internals@gpb.moe> a écrit :
> For naming, maybe the following pair of functions make sense?
> - is_representable_as_int()
Definitely, thank you for proposing. Having a pair of functions for
bidirectional transformations makes much more sense than a single
ambiguous function. Here are some quick specs for what these functions
could do.
is_representable_as_int(mixed $value): bool checks if a given value
can be losslessly converted to an integer.
- Floats: returns true if the float is within PHP_INT_MIN to
PHP_INT_MAX range AND has no fractional part
- Strings: returns true if the string represents a valid integer
within the platform's integer range
- Always returns true for integers
- Special float values: returns false for NaN, INF, -INF
This gives the following example:
```php
is_representable_as_int(42.0); // true
is_representable_as_int(42.5); // false
is_representable_as_int(2**31); // false on 32-bit, true on 64-bit
is_representable_as_int(2**63); // false on both platforms
is_representable_as_int("123"); // true
is_representable_as_int("123.0"); // true
is_representable_as_int("123.5"); // false
is_representable_as_int(NAN); // false
```
> - is_representable_as_float()
Now, is_representable_as_float(mixed $value): bool. The function
would check if a value can be represented as a float without precision
loss.
- Integers: returns true if within the IEEE 754 safe integer range
(+/-(2^53-1)) regardless of the system's PHP_INT_MAX
- Strings: returns true if parseable as a float within safe precision bounds
- Floats always returns true
- The IEEE 754 safe integer limit applies universally
This give the following examples:
```php
is_representable_as_float(2**53 - 1); // true
is_representable_as_float(2**53); // false, precision loss when
casted to float
is_representable_as_float(PHP_INT_MAX); // false on 64-bit, true on 32-bit
is_representable_as_float(42); // true
is_representable_as_float("123.456"); // true
is_representable_as_float("1e308"); // true
is_representable_as_float("1e400"); // false
```
What do you think of this new approach?
Best,
Alexandre Daubois