moneyphp / money

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

Passing currency as string deprecated #613

Closed sportdude closed 4 years ago

sportdude commented 4 years ago

I’m using the example of the DecimalMoneyParser from the docs and getting this notice: PHP Deprecated: Passing a currency as string is deprecated since 3.1 and will be removed in 4.0. Please pass a Money/Currency instance instead. in /var/www/html/vendor/moneyphp/money/src/Parser/DecimalMoneyParser.php on line 55

But if I use something such as: $money = new Money('19.87', new Currency('USD'));

I get the error: InvalidArgumentException with message 'Amount must be an integer(ish) value'

How can I convert this value (19.87) to the lowest unit of money without a decimal?

Thanks

UlrichEckhardt commented 4 years ago

The unit of the currency is the cent, so you pass 1987, either as numeric value or as string.

sportdude commented 4 years ago

Thanks for your input. I don’t have the value 1987, only 19.87. It’s coming from my data source. I’m trying to get the proper int value as doing (int)(19.87*100) is rounding off to 1900.

When I pass a string to the DecimalMoneyParser, I’m getting a notice saying strings will be deprecated and to use Money/Currency. But I’m unable to pass a string containing fractional cents to the Money/Currency instance as the notice tells me to do.

Right now I’m just using str_replace to remove the decimal... but this seems wrong.

UlrichEckhardt commented 4 years ago

Careful, (int)(19.87*100) is not the same as (int)(19.87)*100!

That said, if you get a string of the form xxx.yy with exactly two digits behind the radix separator, using str_replace() is a way to get this to the required format without rounding. Even just parsing 19.87 to a float requires rounding, because it converts between two different bases (10 -> 2) and that doesn't always work without.

Now you just created another puzzle though: You say you are "unable to pass a string containing fractional cents", but if you try that you're mistaken anyway, because the library doesn't want to represent these anyway. I hope you meant "cents" or "fractional dollars", but not "fractional cents"!

sportdude commented 4 years ago

Yes I meant cents. Thanks for all the guidance and helpful information! I will be using the str_replace method. I thought I was doing something improper, but glad to know it’s acceptable. 👍