moneyphp / money

PHP implementation of Fowler's Money pattern.
http://moneyphp.org
MIT License
4.6k stars 440 forks source link

Invalid integer part Invalid digit , found #593

Closed cmodijk closed 4 years ago

cmodijk commented 4 years ago

I'm using version 3.3.0 and i'm getting the following error.

Invalid integer part 25,9500. Invalid digit , found

Example code

$moneyParser = new IntlLocalizedDecimalParser(
    new \NumberFormatter(
        'nl_NL',
        \NumberFormatter::DECIMAL
    ),
    new ISOCurrencies()
);

$moneyParser->parse(
    '25,95',
    new Currency('EUR')
);

The PHP version i'm using is 7.3.8

I also tried the example from the website with cents and it also gives me the same error

Invalid integer part 1000,100. Invalid digit , found
$currencies = new ISOCurrencies();

$numberFormatter = new \NumberFormatter('nl_NL', \NumberFormatter::DECIMAL);
$moneyParser = new IntlLocalizedDecimalParser($numberFormatter, $currencies);

--$money = $moneyParser->parse('1.000,00', new Currency('EUR'));
++$money = $moneyParser->parse('1.000,10', new Currency('EUR'));
frederikbosch commented 4 years ago

The outcome on my machine is this, php 7.3.18.

/srv/libraries/money/test.php:19:
class Money\Money#6 (2) {
  private $amount =>
  string(4) "2595"
  private $currency =>
  class Money\Currency#5 (1) {
    private $code =>
    string(3) "EUR"
  }
}

Does your machine have the right locales installed?

cmodijk commented 4 years ago

For other people that come on this issue I got the error again on a other project and after debugging I found the problem. Somewhere in our application the local was set like this setlocale(LC_ALL, 'nl_NL'); this makes al the floats in PHP act like the local version which for nl_NL is 25,95 instead of 25.95. Money PHP then converts this into a string and then has the wrong notation for parsing this into the money object. I solved this by switching back to setlocale(LC_ALL, 'en_US'); just before using the parsing.

Example code

setlocale(LC_ALL, 'nl_NL');

$numberFormatter = new \NumberFormatter('nl_NL', \NumberFormatter::DECIMAL);
var_dump($numberFormatter->parse('25,95'));
var_dump((string) $numberFormatter->parse('25,95'));

This is the output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.21, 7.4.0 - 7.4.9 in 8.0.0alpha1 - beta1 this seems to be solved.

float(25,95)
string(5) "25,95"

The expected output of this should be.

float(25.95)
string(5) "25.95"

Resources