Skip to content

Commit 7966e7e

Browse files
committed
Adds formatting string to defined thousands separator
1 parent 863ce5f commit 7966e7e

File tree

2 files changed

+19
-10
lines changed

2 files changed

+19
-10
lines changed

src/ElliotJReed/Maths/Number.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,14 @@ public function __construct(self | int | float | string $number = 0, private rea
1717
$this->number = $this->castNumberToString($number);
1818
}
1919

20-
public function asString(?int $decimalPlaces = null): string
20+
public function asString(?int $decimalPlaces = null, string $thousandsSeparator = ''): string
2121
{
2222
if (null !== $decimalPlaces) {
2323
if ($decimalPlaces < 0) {
2424
throw new InvalidDecimalPlaces('Decimal places must be a whole number greater than or equal to 0. Invalid decimal places number: ' . $decimalPlaces);
2525
}
2626

27-
return \number_format((float) $this->number, $decimalPlaces, '.', '');
27+
return \number_format((float) $this->number, $decimalPlaces, '.', $thousandsSeparator);
2828
}
2929

3030
if (\str_contains($this->number, '.')) {

tests/ElliotJReed/Maths/NumberTest.php

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,29 @@ final class NumberTest extends TestCase
1313
{
1414
public function testItReturnsNumberAsStringToDefinedDecimalPlaces(): void
1515
{
16-
$number = new Number(0.29533);
16+
$number = new Number(10000.29533);
1717

18-
$this->assertSame('0.30', $number->asString(2));
19-
$this->assertSame('0.29533', $number->asString());
20-
$this->assertSame(0.29533, $number->asFloat());
18+
$this->assertSame('10000.30', $number->asString(2));
19+
$this->assertSame('10000.29533', $number->asString());
20+
$this->assertSame(10000.29533, $number->asFloat());
2121
}
2222

2323
public function testItReturnsNumberAsWholeNumberStringToZeroDefinedDecimalPlaces(): void
2424
{
25-
$number = new Number(1.29533);
25+
$number = new Number(10000.29533);
2626

27-
$this->assertSame('1', $number->asString(0));
28-
$this->assertSame('1.29533', $number->asString());
29-
$this->assertSame(1.29533, $number->asFloat());
27+
$this->assertSame('10000', $number->asString(0));
28+
$this->assertSame('10000.29533', $number->asString());
29+
$this->assertSame(10000.29533, $number->asFloat());
30+
}
31+
32+
public function testItReturnsNumberAsStringToDefinedThousandsSeparator(): void
33+
{
34+
$number = new Number(10000.29533);
35+
36+
$this->assertSame('10,000.30', $number->asString(2, ','));
37+
$this->assertSame('10000.29533', $number->asString());
38+
$this->assertSame(10000.29533, $number->asFloat());
3039
}
3140

3241
public function testItThrowsExceptionWhenDecimalPlacesArgumentIsLessThanZeroWhenReturningNumberAsAString(): void

0 commit comments

Comments
 (0)