On 04/02/2021 17:54, Benjamin Morel wrote:
On Thu, 4 Feb 2021 at 17:05, G. P. B. <george.bany...@gmail.com> wrote:

Greetings internal,

I'm proposing a new RFC which would warn when an implicit conversion
from float to int occurs.

The draft is currently located on GitHub:
https://github.com/Girgias/float-int-warning/
for ease of commenting/providing changes to it.

The official discussion phase wouldn't start before I convert it to docwiki
and
post it on the wiki, something I'm planning to do next week.

Any feedback is appreciated.

Best regards,

George P. Banyard

Hi George,

Thank you for this proposal, I'm all for it, though I'd go one step
further, and actually issue a warning during explicit casting as well:

(int) 3.5; // E_WARNING
(int) round(3.5); // OK

In my experience, it's better to be explicit about your intent, so forcing
the user to round() before casting when the float has a fractional part is
OK to me.
This would help prevent weird silent conversions such as when you cast to
(int) from user input:

$age = $_GET['age']; // '25.75'
$x = (int) $foo; // I'd expect a warning, not a silent conversion to 25

— Benjamin


There are legitimate cases for explicitly casting floats to int. For example floor() outputs a float, but in the context of the domain I'm working I might know that the result is never going to exceed a certain value and want the result explicitly as an int.

(And after checking the manual, I'd also note here that round() also returns a float, so how exactly does your example here work? Is it only OK to explictly cast a float that's the return value of a function? Or only explictly cast a float if the fractional part is .0? Is that viable given the "inaccuracy" of floats? Or would it be better for PHP to have some non-range/accuracy-sensitive representation for integers (and decimals) here?) (and now we're getting into "why are we still using floating point math by default in 2021" territory, so I'll stop right here)

AllenJB


PS. Apologies for the dupe to those who did receive my original send, but I forgot to amend my from address to my subscribed address and as I recall the list doesn't like list-only replies)

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to