Skip to content

Commit

Permalink
Add a Number::toCurrency() helper
Browse files Browse the repository at this point in the history
  • Loading branch information
caendesilva committed Nov 1, 2023
1 parent d59942b commit 8151a80
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Illuminate/Support/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,23 @@ public static function toHuman($number, $locale = 'en')
return $formatter->format($number);
}

/**
* Format the number to a currency format.
*
* @param float|int $number
* @param string $currency
* @param string $locale
* @return false|string
*/
public static function toCurrency($number, $currency = 'USD', $locale = 'en')
{
static::needsIntlExtension();

$formatter = new NumberFormatter($locale, NumberFormatter::CURRENCY);

return $formatter->formatCurrency($number, $currency);
}

/**
* Format the number of bytes to a human-readable string.
*
Expand Down
30 changes: 30 additions & 0 deletions tests/Support/SupportNumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,36 @@ public function testToHumanWithDifferentLocale()
$this->assertSame('ett­hundra­tjugo­tre', Number::toHuman(123, 'sv'));
}

public function testToCurrency()
{
$this->needsIntlExtension();

$this->assertSame('$0.00', Number::toCurrency(0));
$this->assertSame('$1.00', Number::toCurrency(1));
$this->assertSame('$10.00', Number::toCurrency(10));

$this->assertSame('€0.00', Number::toCurrency(0, 'EUR'));
$this->assertSame('€1.00', Number::toCurrency(1, 'EUR'));
$this->assertSame('€10.00', Number::toCurrency(10, 'EUR'));

$this->assertSame('-$5.00', Number::toCurrency(-5));
$this->assertSame('$5.00', Number::toCurrency(5.00));
$this->assertSame('$5.32', Number::toCurrency(5.325));
}

public function testToCurrencyWithDifferentLocale()
{
$this->needsIntlExtension();

$this->assertSame('1,00 €', Number::toCurrency(1, 'EUR', 'de'));
$this->assertSame('1,00 $', Number::toCurrency(1, 'USD', 'de'));
$this->assertSame('1,00 £', Number::toCurrency(1, 'GBP', 'de'));

$this->assertSame('123.456.789,12 $', Number::toCurrency(123456789.12345, 'USD', 'de'));
$this->assertSame('123.456.789,12 €', Number::toCurrency(123456789.12345, 'EUR', 'de'));
$this->assertSame('1 234,56 $US', Number::toCurrency(1234.56, 'USD', 'fr'));
}

public function testBytesToHuman()
{
$this->assertSame('0 B', Number::bytesToHuman(0));
Expand Down

0 comments on commit 8151a80

Please sign in to comment.