ArrayUtil.php
5 years ago
DatabaseUtil.php
4 years ago
NumberUtil.php
5 years ago
StringUtil.php
5 years ago
NumberUtil.php
35 lines
| 1 | <?php |
| 2 | /** |
| 3 | * A class of utilities for dealing with numbers. |
| 4 | */ |
| 5 | |
| 6 | namespace Automattic\WooCommerce\Utilities; |
| 7 | |
| 8 | /** |
| 9 | * A class of utilities for dealing with numbers. |
| 10 | */ |
| 11 | final class NumberUtil { |
| 12 | |
| 13 | /** |
| 14 | * Round a number using the built-in `round` function, but unless the value to round is numeric |
| 15 | * (a number or a string that can be parsed as a number), apply 'floatval' first to it |
| 16 | * (so it will convert it to 0 in most cases). |
| 17 | * |
| 18 | * This is needed because in PHP 7 applying `round` to a non-numeric value returns 0, |
| 19 | * but in PHP 8 it throws an error. Specifically, in WooCommerce we have a few places where |
| 20 | * round('') is often executed. |
| 21 | * |
| 22 | * @param mixed $val The value to round. |
| 23 | * @param int $precision The optional number of decimal digits to round to. |
| 24 | * @param int $mode A constant to specify the mode in which rounding occurs. |
| 25 | * |
| 26 | * @return float The value rounded to the given precision as a float, or the supplied default value. |
| 27 | */ |
| 28 | public static function round( $val, int $precision = 0, int $mode = PHP_ROUND_HALF_UP ) : float { |
| 29 | if ( ! is_numeric( $val ) ) { |
| 30 | $val = floatval( $val ); |
| 31 | } |
| 32 | return round( $val, $precision, $mode ); |
| 33 | } |
| 34 | } |
| 35 |