Skip to content

Commit

Permalink
Optimized Number helper (#554)
Browse files Browse the repository at this point in the history
Co-authored-by: Deeka Wong <[email protected]>
  • Loading branch information
huangdijia and huangdijia authored Feb 5, 2024
1 parent 47d09a9 commit 32210e7
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,18 @@ public static function format(int|float $number, ?int $precision = null, ?int $m
*
* @return string
*/
public static function spell(int|float $number, ?string $locale = null)
public static function spell(int|float $number, ?string $locale = null, ?int $after = null, ?int $until = null)
{
static::ensureIntlExtensionIsInstalled();

if (! is_null($after) && $number <= $after) {
return static::format($number, locale: $locale);
}

if (! is_null($until) && $number >= $until) {
return static::format($number, locale: $locale);
}

$formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::SPELLOUT);

return $formatter->format($number);
Expand Down Expand Up @@ -127,21 +135,19 @@ public static function fileSize(int|float $bytes, int $precision = 0, ?int $maxP
}

/**
* Convert the number to its human readable equivalent.
* Convert the number to its human-readable equivalent.
*
* @param int $number
* @return string
* @return bool|string
*/
public static function abbreviate(int|float $number, int $precision = 0, ?int $maxPrecision = null)
{
return static::forHumans($number, $precision, $maxPrecision, abbreviate: true);
}

/**
* Convert the number to its human readable equivalent.
* Convert the number to its human-readable equivalent.
*
* @param int $number
* @return string
* @return bool|string
*/
public static function forHumans(int|float $number, int $precision = 0, ?int $maxPrecision = null, bool $abbreviate = false)
{
Expand Down Expand Up @@ -222,7 +228,9 @@ protected static function summarize(int|float $number, int $precision = 0, ?int
protected static function ensureIntlExtensionIsInstalled()
{
if (! extension_loaded('intl')) {
throw new RuntimeException('The "intl" PHP extension is required to use this method.');
$method = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function'];

throw new RuntimeException('The "intl" PHP extension is required to use the [' . $method . '] method.');
}
}
}

0 comments on commit 32210e7

Please sign in to comment.