Re: [RFC] Add "is_representable_as_float()" and "is_representable_as_int()" functions

From: Date: Tue, 26 Aug 2025 18:33:00 +0000
Subject: Re: [RFC] Add "is_representable_as_float()" and "is_representable_as_int()" functions
References: 1 2 3 4  Groups: php.internals 
Request: Send a blank email to internals+get-128565@lists.php.net to get a copy of this message

On Tue, Aug 26, 2025, at 20:23, Tim Düsterhus wrote:
> Hi
> 
> On 8/26/25 19:14, Alexandre Daubois wrote:
> >> 3.14 is not exactly representable as a IEEE-754 double-precision
> >> floating point number. The two nearest representable values are
> >> 3.14000000000000012434 (this one is the nearest) and
> >> 3.13999999999999968026. Returning true for
> >> is_representable_as_float("3.14") is therefore wrong to me.
> > 
> > You're right about mathematical precision. Perhaps the function name
> > is misleading. What the function actually should check is whether a
> > string > float > string roundtrip preserves the value as PHP
> > developers would expect it, not whether it's mathematically exactly
> > representable in IEEE-754.
> > 
> > Maybe a more accurate name would better reflect this behavior. Naming
> > is super hard again here. The goal is pragmatic: "will this value
> > survive a type conversion cycle without surprising changes?"
> 
> "Surprising changes" is not a meaningful term. Keep in mind that the 
> behavior of the function will need to be accurately documented and that 
> folks need something to work with to determine whether a report is valid 
> or not when bugs in the function get reported - which will inevitably 
> happen.
> 
> In fact to use one of the examples for the RFC: 1e10 does not roundtrip.
> 
>      php > var_dump((string)(float)"1e10");
>      string(11) "10000000000"
> 
> "1e10" clearly is different than "10000000000".
> 
> Generally speaking, I'm also not sure if “printing raw floats” is a 
> use-case we should encourage. Instead almost any application will need 
> to format a number for a specific use-case. Formatting numbers for human 
> consumption [1] has different requirements compared to formatting 
> numbers for programmatic consumption.

Indeed. In some parts of the world, 1.000,01 is interpreted as 1000.01 in computers. That format
also doesn’t roundtrip but is a valid numeric string, depending on locale.

— Rob


Thread (28 messages)

« previous php.internals (#128565) next »