File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed
Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ <?php declare (strict_types = 1 );
2+
3+ namespace Utilitte \Php ;
4+
5+ final class Money
6+ {
7+
8+ public static function formatShort (int $ value , int $ precision = 1 ): string
9+ {
10+ // 1_000
11+ if ($ value < 1000 ) {
12+ return self ::formatMoney ($ value , $ precision );
13+ } elseif ($ value < 1000000 ) {
14+ // 1_000_000
15+ return self ::formatMoney ($ value / 1000 , $ precision ) . 'K ' ;
16+ } elseif ($ value < 1000000000 ) {
17+ // 1_000_000_000
18+ return self ::formatMoney ($ value / 1000000 , $ precision ) . 'M ' ;
19+ } elseif ($ value < 1000000000000 ) {
20+ // 1_000_000_000_000
21+ return self ::formatMoney ($ value / 1000000000 , $ precision ) . 'B ' ;
22+ }
23+
24+ return self ::formatMoney ($ value / 1000000000000 , $ precision ) . 'T ' ;
25+ }
26+
27+ private static function formatMoney (float $ value , int $ precision ): string
28+ {
29+ return rtrim (number_format ($ value , $ precision ), '0. ' );
30+ }
31+
32+ }
Original file line number Diff line number Diff line change 1+ <?php declare (strict_types = 1 );
2+
3+ use Tester \Assert ;
4+ use Utilitte \Php \Money ;
5+
6+ require __DIR__ . '/../bootstrap.php ' ;
7+
8+ Assert::same ('1K ' , Money::formatShort (1000 ));
9+ Assert::same ('1.3K ' , Money::formatShort (1254 ));
10+ Assert::same ('1.254K ' , Money::formatShort (1254 , 3 ));
11+ Assert::same ('1M ' , Money::formatShort (1000 *1000 ));
You can’t perform that action at this time.
0 commit comments