Skip to content

Commit a93960f

Browse files
authored
feat(Support): Add number parsing methods to Number class (#861)
* feat(Support): Add number parsing methods to Number class * refactor(Number): 移除 parse 方法及其相关方法的返回类型注释 --------- Co-authored-by: Deeka Wong <[email protected]>
1 parent 222f102 commit a93960f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/Number.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,37 @@ public static function format(int|float $number, ?int $precision = null, ?int $m
4848
return $formatter->format($number);
4949
}
5050

51+
/**
52+
* Parse the given string according to the specified format type.
53+
*/
54+
public static function parse(string $string, ?int $type = NumberFormatter::TYPE_DOUBLE, ?string $locale = null): int|float
55+
{
56+
static::ensureIntlExtensionIsInstalled();
57+
58+
$formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::DECIMAL);
59+
60+
return $formatter->parse($string, $type);
61+
}
62+
63+
/**
64+
* Parse a string into an integer according to the specified locale.
65+
*/
66+
public static function parseInt(string $string, ?string $locale = null): int
67+
{
68+
return self::parse($string, NumberFormatter::TYPE_INT32, $locale);
69+
}
70+
71+
/**
72+
* Parse a string into a float according to the specified locale.
73+
*
74+
* @param string $string The string to parse
75+
* @param string|null $locale The locale to use
76+
*/
77+
public static function parseFloat(string $string, ?string $locale = null): float
78+
{
79+
return self::parse($string, NumberFormatter::TYPE_DOUBLE, $locale);
80+
}
81+
5182
/**
5283
* Spell out the given number in the given locale.
5384
*

0 commit comments

Comments
 (0)