[wp-trac] [WordPress Trac] #46346: WP_List_Table calculates total_pages as a float

WordPress Trac noreply at wordpress.org
Tue Jan 26 12:46:21 UTC 2021


#46346: WP_List_Table calculates total_pages as a float
----------------------------+-----------------------------
 Reporter:  lev0            |       Owner:  SergeyBiryukov
     Type:  defect (bug)    |      Status:  reviewing
 Priority:  normal          |   Milestone:  5.7
Component:  Administration  |     Version:
 Severity:  minor           |  Resolution:
 Keywords:  has-patch       |     Focuses:
----------------------------+-----------------------------

Comment (by jrf):

 I've reviewed the patch and am not a fan.

 Using `( (bool) $over )` and then trusting PHP to do the type juggling to
 integers is not a good idea.
 1. It's "clever" code which is [https://developer.wordpress.org/coding-
 standards/wordpress-coding-standards/php/#clever-code strongly
 discouraged]. It requires more cognitive load than is necessary.
 2. While it may work now, with PHP becoming stricter all the time, this
 may well stop working soon enough.

 Something like  `( $over > 0 ? 1 : 0 )` would already make the code a lot
 more self-explanatory and is not prone to the same issues.

 Otherwise, an alternative solution would be:
 {{{#!php
 <?php
 $args['total_pages'] = (int) round( ceil( $args['total_items'] /
 $args['per_page'] ), 0); // Using round to prevent floating point issues.
 }}}


 To be fair, I've also ran tests with the old versus the new code with a
 large number of variations of "total items" and "per page", I could not
 get it to find a combination where we'd get a rounding error if just using
 `(int) ceil()`, so unless a specific case can be identified where we would
 get a rounding error, the simplest solution - i.e. `(int) ceil()` - would
 be the best one.

 Note: if you want precision calculations with floats, the
 [https://www.php.net/manual/en/book.bc.php BCMath extension] should always
 be preferred.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/46346#comment:7>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list