PHP和Money,将钱转换成美分

Jus*_*tin 3 php mysql currency money-format

所以我对如何在数据库中存储"钱"进行了一些研究,我认为我想要使用的系统是

将Money转换为CENTS,然后将CENTS存储在字段类型为DECIMAL(19,4)的MySQL DB中.

我的问题是,如果我有一个来自用户的输入字段...我该如何处理多种输入类型.IE:

$input = "1,346.54"
$input = "10,985.23"
$input = "110,400.50"
$input = "1033.44"
Run Code Online (Sandbox Code Playgroud)

等等......

将此转换为CENTS的最佳方法是什么?因为我们必须处理'字符串'并将它们转换为INT,然后除以100 ...我尝试的所有内容都会因为与数字的"逗号"分离而引发问题.

任何想法或方向将不胜感激.

小智 7

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;
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*wie 6

看起来有一个NumberFormatter类提供了一个parseCurrency方法.请查看http://www.php.net/manual/en/numberformatter.parsecurrency.php

提供的示例是

$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89 $";
echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n";
Run Code Online (Sandbox Code Playgroud)

  • +1 PHP为我们提供了这些不错的类,为什么要通过创建自定义解析器重新发明轮子? (2认同)