Skip to content
This repository was archived by the owner on Dec 27, 2023. It is now read-only.

Commit dcf28c9

Browse files
author
Stefan Majoor
committed
Added mod to decimal
1 parent 6772755 commit dcf28c9

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/Decimal.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,7 @@ public function additiveInverse()
548548
return new Decimal($value, $this->scale);
549549
}
550550

551+
551552
/**
552553
* "Rounds" the Decimal to have at most $scale digits after the point
553554
* @param integer $scale
@@ -620,6 +621,18 @@ public function abs()
620621
return $this->additiveInverse();
621622
}
622623

624+
/**
625+
* Calculate modulo with a decimal
626+
* @param $d
627+
* @return $this % $d
628+
*/
629+
public function mod(Decimal $d, $scale = null)
630+
{
631+
// integer division
632+
$div = $this->div($d, 1)->floor();
633+
return $this->sub($div->mul($d, $scale));
634+
}
635+
623636
public function hasSameSign(Decimal $b) {
624637
return $this->isPositive() && $b->isPositive() || $this->isNegative() && $b->isNegative();
625638
}

tests/Decimal/DecimalModTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
use Litipk\BigNumbers\Decimal as Decimal;
4+
5+
/**
6+
* @group mod
7+
*/
8+
class DecimalModTest extends PHPUnit_Framework_TestCase
9+
{
10+
public function modProvider() {
11+
return array(
12+
array('10', '3', '1'),
13+
array('34', '3.4', '0'),
14+
array('15.1615', '3.156156', '2.536876'),
15+
array('15.1615', '3.156156', '2.5365', 3),
16+
);
17+
}
18+
/**
19+
* @dataProvider modProvider
20+
*/
21+
public function testMod($number, $mod, $answer, $scale = null) {
22+
$numberDec = Decimal::fromString($number);
23+
$modDec = Decimal::fromString($mod);
24+
$decimalAnswer = $numberDec->mod($modDec, $scale);
25+
26+
$this->assertTrue(
27+
Decimal::fromString($answer)->equals($decimalAnswer),
28+
$decimalAnswer . ' must be equal to ' . $answer
29+
);
30+
}
31+
}

0 commit comments

Comments
 (0)