Skip to content

Commit e3f6641

Browse files
committed
add Money
1 parent 1711afe commit e3f6641

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/Money.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
}

tests/cases/money.formatShort.phpt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
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));

0 commit comments

Comments
 (0)