Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue #3044185: Add roundDown() to Price Calculator. #871

Open
wants to merge 1 commit into
base: 8.x-2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions modules/price/src/Calculator.php
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,31 @@ public static function round($number, $precision = 0, $mode = PHP_ROUND_HALF_UP)
return $number;
}

/**
* Rounds the given number down to the given precision.
*
* @param string $number
* The number.
* @param int $precision
* The number of decimals to round to.
*
* @return string
* The rounded number.
*
* @throws \InvalidArgumentException
* Thrown when an invalid (non-numeric or negative) precision is given.
*/
public static function roundDown($number, $precision = 0) {
self::assertNumberFormat($number);
if (!is_numeric($precision) || $precision < 0) {
throw new \InvalidArgumentException('The provided precision should be a positive number');
}

$base = bcpow(10, $precision);
return self::divide(self::floor(self::multiply($number, $base, self::getPrecision($number))), $base, $precision);

}

/**
* Compares the first number to the second number.
*
Expand Down Expand Up @@ -244,6 +269,23 @@ public static function trim($number) {
return $number;
}

/**
* Get the precision of a number.
*
* @param string $number
* The number to determine precision.
*
* @return int
* The numbers precision.
*/
public static function getPrecision($number) {
$check = explode('.', $number);
if (!empty($check[1])) {
return strlen($check[1]);
}
return 0;
}

/**
* Assert that the given number is a numeric string value.
*
Expand Down
10 changes: 10 additions & 0 deletions modules/price/tests/src/Unit/CalculatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public function testComparison() {
* @covers ::ceil
* @covers ::floor
* @covers ::round
* @covers ::roundDown
*/
public function testRounding() {
$this->assertEquals('5', Calculator::ceil('4.4'));
Expand Down Expand Up @@ -90,6 +91,15 @@ public function testRounding() {
foreach ($rounding_data as $item) {
$this->assertEquals($item[3], Calculator::round($item[0], $item[1], $item[2]));
}

$this->assertEquals('1.95', Calculator::roundDown('1.95583', 2));
}

/**
* @covers ::getPrecision
*/
public function testPrecision() {
$this->assertEquals(2, Calculator::getPrecision('1.99'));
}

}