wp_fuzzy_number_match()
Checks how close two numbers are to each other, taking into account an allowed tolerance.
The function compares the expected value with the actual one and considers them matching if the difference between them is not greater than the specified precision.
This is useful when you need to compare floating-point numbers where a small error is acceptable.
Note: the function does not round the numbers. It simply calculates the absolute difference between them and compares it with $precision.
No Hooks.
Returns
true|false.
true— the numbers differ by no more than the specified precision.false— the difference between the numbers is greater.
Usage
wp_fuzzy_number_match( $expected, $actual, $precision );
- $expected(int|float) (required)
- The expected value.
- $actual(int|float) (required)
- The actual value to compare with the expected one.
- $precision(int|float)
- The allowable difference between the numbers.
Default: 1
Examples
#1 Default Precision Number Check
Numbers are considered matching because the difference between them is less than or equal to 1.
$expected = 100;
$actual = 100.8;
if ( wp_fuzzy_number_match( $expected, $actual ) ) {
echo 'The numbers are close enough.';
} #2 More strict precision check
In this example, the numbers must not differ by more than 0.1.
$expected = 10.5;
$actual = 10.55;
if ( wp_fuzzy_number_match( $expected, $actual, 0.1 ) ) {
echo 'Value matches.';
} else {
echo 'Value differs too much.';
} #3 Comparison of the computation result
Useful when working with fractional numbers, where the result may differ slightly due to the specifics of calculations.
$expected_total = 19.99;
$actual_total = 20 - 0.01;
if ( wp_fuzzy_number_match( $expected_total, $actual_total, 0.001 ) ) {
echo 'Final total matches.';
}
Changelog
| Since 5.3.0 | Introduced. |
wp_fuzzy_number_match() wp fuzzy number match code WP 7.0
function wp_fuzzy_number_match( $expected, $actual, $precision = 1 ) {
return abs( (float) $expected - (float) $actual ) <= $precision;
}