Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and Money, converting money to cents

So I have done a fair bit of research on how to store "money" in a database and I think the system I want to use is

Converting Money into CENTS and then storing the CENTS in a MySQL DB with a field type of DECIMAL (19,4).

My question is, IF I have an input field from the user... how do I deal with multiple input types. IE:

$input = "1,346.54"
$input = "10,985.23"
$input = "110,400.50"
$input = "1033.44"

etc etc...

What would be the best method for converting this to CENTS? As we have to deal with 'strings' and convert them to INT, and divide by 100... Everything that I try throws issues because of the "comma" separation with the numbers.

Any thoughts or direction would be greatly appreciated.

like image 679
Justin Avatar asked Dec 07 '22 20:12

Justin


2 Answers

function getMoneyAsCents($value)
{
    // strip out commas
    $value = preg_replace("/\,/i","",$value);
    // strip out all but numbers, dash, and dot
    $value = preg_replace("/([^0-9\.\-])/i","",$value);
    // make sure we are dealing with a proper number now, no +.4393 or 3...304 or 76.5895,94
    if (!is_numeric($value))
    {
        return 0.00;
    }
    // convert to a float explicitly
    $value = (float)$value;
    return round($value,2)*100;
}
like image 194
Justin Avatar answered Dec 09 '22 09:12

Justin


Looks like there is a NumberFormatter class which provides a parseCurrency method. Have a look at http://www.php.net/manual/en/numberformatter.parsecurrency.php

The example provided is

$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89 $";
echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n";
like image 37
Rob Cowie Avatar answered Dec 09 '22 10:12

Rob Cowie