Numbers\round()

transformer returns Closure pure throws
number → (number → float)
At a glance — Bind a decimal precision; the returned Closure rounds any number to that many places. Always returns a float. Throws InvalidArgumentException on non-number input.

Creates a Closure that rounds any number passed to it to a pre-defined number of decimal places. Result is always returned as a float.

/**
  * @param int|float $precision Number of decimal places. Defaults to 1.
  * @return Closure(int|float):float
  * @throws InvalidArgumentException If $precision is not int or float.
  */
Numbers\round($precision = 1): Closure

Returned Closure

When Numbers\round() is called, it returns the following Closure which can be used like a regular function.

/**
  * @param int|float $value
  * @return float
  * @throws InvalidArgumentException If $value is not int or float.
  */
$function (int|float $value): float

Examples

Partial Application

This can be used to create a simple closure which can be used as a regular function.

// Create a function that rounds to 2 decimal places.
$round2dp = Numbers\round(2);

// Called as a function.
echo $round2dp(3.14159); // 3.14
echo $round2dp(2.71828); // 2.72
echo $round2dp(10);      // 10.0

// Used in a higher order function.
$array = array_map($round2dp, [1.2345, 6.789, 0.0001]);
print_r($array); // [1.23, 6.79, 0.0]

Curried

This can be called inline using currying.

echo Numbers\round(0)(3.7); // 4.0

Inlined with Higher Order Function

If you are not planning on reusing the Closure created, you can just call it inline with a higher order function as its callable.

$array = array_map(Numbers\round(2), [1.2345, 6.789]);
print_r($array); // [1.23, 6.79]

Details

Numbers Functions

Releated Number transform Functions