Skip to content

Commit 71bea64

Browse files
committed
fix(Helpers): preserve ValueError on negative precision in format_number()
1 parent 6ae454f commit 71bea64

2 files changed

Lines changed: 10 additions & 1 deletion

File tree

‎system/Helpers/number_helper.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ function format_number(float $num, int $precision = 1, ?string $locale = null, a
151151
} else {
152152
// In order to specify a precision, we'll have to modify
153153
// the pattern used by NumberFormatter.
154-
$pattern = '#,##0' . ($precision > 0 ? '.' . str_repeat('#', $precision) : '');
154+
$pattern = $precision === 0 ? '#,##0' : '#,##0.' . str_repeat('#', $precision);
155155

156156
$formatter->setPattern($pattern);
157157
$output = $formatter->format($num);

‎tests/system/Helpers/NumberHelperTest.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use CodeIgniter\Test\CIUnitTestCase;
1717
use PHPUnit\Framework\Attributes\Group;
18+
use ValueError;
1819

1920
/**
2021
* @internal
@@ -63,6 +64,14 @@ public function testFormatNumberWithPrecision(): void
6364
$this->assertSame('123,456.79', format_number(123456.789, 2, 'en_US'));
6465
}
6566

67+
public function testFormatNumberWithNegativePrecisionThrowsValueError(): void
68+
{
69+
$this->expectException(ValueError::class);
70+
$this->expectExceptionMessage('str_repeat(): Argument #2 ($times) must be greater than or equal to 0');
71+
72+
format_number(123456, -1, 'en_US');
73+
}
74+
6675
public function testFormattingOptions(): void
6776
{
6877
$options = [

0 commit comments

Comments
 (0)