Skip to content

Commit

Permalink
Add a Number::toHuman() helper
Browse files Browse the repository at this point in the history
This is unfortunately dependent on the `ext-intl`, as it wraps the NumberFormatter class.
  • Loading branch information
caendesilva committed Oct 29, 2023
1 parent fb0e6ce commit 7cfa92a
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/Illuminate/Support/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,27 @@

namespace Illuminate\Support;

use NumberFormatter;
use Illuminate\Support\Traits\Macroable;

class Number
{
use Macroable;

/**
* Format the number to a fluent human-readable string.
*
* @param float|int $number
* @param string $locale
* @return false|string
*/
public static function toHuman($number, $locale = 'en')
{
$formatter = new NumberFormatter($locale, NumberFormatter::SPELLOUT);

return $formatter->format($number);
}

/**
* Format the number of bytes to a human-readable string.
*
Expand Down
34 changes: 34 additions & 0 deletions tests/Support/SupportNumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,40 @@

class SupportNumberTest extends TestCase
{
public function testToHuman()
{
$this->assertSame('zero', Number::toHuman(0));
$this->assertSame('one', Number::toHuman(1));
$this->assertSame('ten', Number::toHuman(10));
$this->assertSame('twenty-five', Number::toHuman(25));
$this->assertSame('one hundred', Number::toHuman(100));
$this->assertSame('one hundred thousand', Number::toHuman(100000));
$this->assertSame('one hundred twenty-three million four hundred fifty-six thousand seven hundred eighty-nine', Number::toHuman(123456789));

$this->assertSame('one billion', Number::toHuman(1000000000));
$this->assertSame('one trillion', Number::toHuman(1000000000000));
$this->assertSame('one quadrillion', Number::toHuman(1000000000000000));
$this->assertSame('1,000,000,000,000,000,000', Number::toHuman(1000000000000000000));

$this->assertSame('minus one', Number::toHuman(-1));
$this->assertSame('minus ten', Number::toHuman(-10));
$this->assertSame('minus twenty-five', Number::toHuman(-25));

$this->assertSame('zero point two', Number::toHuman(0.2));
$this->assertSame('one point two three', Number::toHuman(1.23));
$this->assertSame('minus one point two three', Number::toHuman(-1.23));
$this->assertSame('one hundred twenty-three point four five six', Number::toHuman(123.456));
}

public function testToHumanWithDifferentLocale()
{
$this->assertSame('cent vingt-trois', Number::toHuman(123, 'fr'));

$this->assertSame('ein­hundert­drei­und­zwanzig', Number::toHuman(123, 'de'));

$this->assertSame('ett­hundra­tjugo­tre', Number::toHuman(123, 'sv'));
}

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

0 comments on commit 7cfa92a

Please sign in to comment.