PHP 和 Money,将钱转换为美分

标签 php mysql currency money-format

所以我对如何在数据库中存储“钱”做了一些研究,我想我想使用的系统是

将货币转换为 CENTS,然后将 CENTS 存储在字段类型为 DECIMAL (19,4) 的 MySQL 数据库中。

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

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

等等等等......

将其转换为 CENTS 的最佳方法是什么?由于我们必须处理“字符串”并将它们转换为 INT,然后除以 100...我尝试的所有操作都会因为数字的“逗号”分隔而引发问题。

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

最佳答案

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;
}

关于PHP 和 Money,将钱转换为美分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6629253/

相关文章:

php - apache mod_rewrite 中的奇怪行为

mysql - 在数据库中存储两个位置之间的路线

mysql - SQL 从 2 个表中选择并按月分组

mysql - 将一个表的值关联到另一个表

java - 比利时荷兰语的正确货币格式是什么?

php - 重新声明 file_get_html simple_html_dom.php

php - 如何通过 file_get_contents 获取文件扩展名

PHP、MySQL : Display only required parts of my website in sister website

ios - iOS 中的欧元货币格式化程序在数字之前/之后移动符号

asp.net - 更改货币格式