Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP money string conversion to integer error

I have a small financial application with PHP as the front end and MySQL as the back end. I have ancient prejudices, and I store money values in MySQL as an integer of cents. My HTML forms allow input of dollar values, like "156.64" and I use PHP to convert that to cents and then I store the cents in the database.

I have a function that both cleans the dollar value from the form, and converts it to cents. I strip leading text, I strip trailing text, I multiply by 100 and convert to an integer. That final step is

$cents = (integer) ($dollars * 100);

This works fine for almost everything, except for a very few values like '156.64' which consistently converts to 15663 cents. Why does it do this?

If I do this:

$cents = (integer) ($dollars * 100 + 0.5);

then it consistently works. Why do I need to add that rounding value?

Also, my prejudices about storing money amounts as integers and not floating point values, is that no longer needed? Will modern float calculations produce nicely rounded and accurate money values adequate for keeping 100% accurate accounting?

like image 857
codebunny Avatar asked Dec 13 '22 06:12

codebunny


1 Answers

If you want precision, you should store your money values using the DECIMAL data type in MySQL.

like image 121
Christian C. Salvadó Avatar answered Dec 23 '22 22:12

Christian C. Salvadó