35 $this->formatter = $formatter;
36 $this->currencies = $currencies;
42 public function parse($money, $forceCurrency =
null)
44 if (!is_string($money)) {
45 throw new ParserException(
'Formatted raw money should be string, e.g. $1.00');
49 $decimal = $this->formatter->parseCurrency($money, $currency);
51 if (
false === $decimal) {
53 'Cannot parse '.$money.
' to Money. '.$this->formatter->getErrorMessage()
57 if (
null !== $forceCurrency) {
58 $currency = $forceCurrency;
67 if (!$currency instanceof
Currency) {
68 @trigger_error(
'Passing a currency as string is deprecated since 3.1 and will be removed in 4.0. Please pass a '.Currency::class.
' instance instead.', E_USER_DEPRECATED);
72 $decimal = (string) $decimal;
73 $subunit = $this->currencies->subunitFor($currency);
74 $decimalPosition = strpos($decimal,
'.');
76 if (
false !== $decimalPosition) {
77 $decimalLength = strlen($decimal);
78 $fractionDigits = $decimalLength - $decimalPosition - 1;
79 $decimal = str_replace(
'.',
'', $decimal);
82 if ($fractionDigits > $subunit) {
83 $decimal = substr($decimal, 0, $decimalPosition + $subunit);
84 } elseif ($fractionDigits < $subunit) {
85 $decimal .= str_pad(
'', $subunit - $fractionDigits,
'0');
88 $decimal .= str_pad(
'', $subunit,
'0');
91 if (
'-' === $decimal[0]) {
92 $decimal =
'-'.ltrim(substr($decimal, 1),
'0');
94 $decimal = ltrim($decimal,
'0');
97 if (
'' === $decimal) {
101 return new Money($decimal, $currency);