PHP 和 Money,将钱兑换成美分

发布于 2024-11-19 07:11:04 字数 382 浏览 2 评论 0原文

因此,我对如何在数据库中存储“钱”进行了相当多的研究,我认为我想要使用的系统是

将钱转换为美分,然后将美分存储在字段类型为 DECIMAL (19 ,4)。

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

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

等等等等...

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

み青杉依旧 2024-11-26 07:11:05
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;
}
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;
}
無心 2024-11-26 07:11:05

看起来有一个 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";

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";
踏雪无痕 2024-11-26 07:11:05

您可以像这样删除逗号:

$input = str_replace( ',', '', $input);

此时,您可以通过转换为浮点数并乘以 100 来转换为分。但是,这可能是不必要的。在执行数学运算时,您可能会遇到精度问题,但只需将值存储在数据库中就可以以原始形式完成,而无需更改值(假设您的数据库表结构正确):

$input = (float)str_replace( ',', '', $input);

You can remove the commas like this:

$input = str_replace( ',', '', $input);

At this point, you can convert to cents by converting to a float and multiplying by 100. However, this is probably unnecessary. You would potential encounter precision issues when performing math operations, but simply storing the values in the database can be done in the original form without alteration of the value (assuming your DB tables are properly structured):

$input = (float)str_replace( ',', '', $input);
情话墙 2024-11-26 07:11:05
function convert_to_cents($v)
  {
    $v = str_replace(',','',$v);
    $p = explode('.',$v);
    if(strlen($p[1])<2){ $p[1] = $p[1]*10;}
    return ($p[0]*100)+$p[1];
  }
function convert_to_cents($v)
  {
    $v = str_replace(',','',$v);
    $p = explode('.',$v);
    if(strlen($p[1])<2){ $p[1] = $p[1]*10;}
    return ($p[0]*100)+$p[1];
  }
坦然微笑 2024-11-26 07:11:05

这会将大多数十进制货币转换为其子单位。

$1,234,567.89 = 123456789

£ 1,234,567.89 = 123456789

€1.234.567,89 = 123456789

12,34 欧元 = 1234

12,34 € = 1234

12,30 € = 1230

1,2 = 102

function convertDecimalCurrencyToSubUnit($str)
{
    if( preg_match('/^(.+)[^\d](\d|\d\d)[^\d]*$/', $str, $m) )
        return intval(preg_replace('/[^\d]/', '', $m[1]) . ( (strlen($m[2])>1) ? $m[2] : ('0' . $m[2]) ));
    return 0;
}

This converts most of the decimal currencies to their subunits.

$1,234,567.89 = 123456789

£ 1,234,567.89 = 123456789

€1.234.567,89 = 123456789

12,34 EUR = 1234

12,34 € = 1234

12,30 € = 1230

1,2 = 102

function convertDecimalCurrencyToSubUnit($str)
{
    if( preg_match('/^(.+)[^\d](\d|\d\d)[^\d]*$/', $str, $m) )
        return intval(preg_replace('/[^\d]/', '', $m[1]) . ( (strlen($m[2])>1) ? $m[2] : ('0' . $m[2]) ));
    return 0;
}
自由范儿 2024-11-26 07:11:05

可能只是删除“,”和“。”从字符串中,结果是以美分为单位的金额。

Probably just remove the ',' and the '.' from the string, the result is the amount in cents.

笑饮青盏花 2024-11-26 07:11:05

您可能需要使用 strrpos 从后面解析字符串...如果您在距离末尾 2 个位置处找到逗号,那么可以安全地假设其为外币,这些是美分...一旦确定,请使用一个正则表达式来去除剩余的逗号(当然是在将“CENTS”逗号转换为小数之后)...现在您有一个正常的 DEC 数字可以使用。

使用它来查找字符串中的最后一个逗号... strrpos

使用它来替换逗号 preg_replace

这是一个有用的正则表达式网站.. regexlib

//Finding the last comma

$yourCommaPos = strrpos($myString, ',');
if ($yourCommaPos == strlen($myString) - 2) {
 //Comma is foreign currency decimal
 // Replace with '.'
} else {
 //Not foreign Currency so...
 //Strip Commas
 preg_replace(',', '', $myString);
}

You will probably need to parse the string from the back using strrpos ... If you find a comma 2 spots from the end, then its prob safe to assume its foreign currency and those are the CENTS... Once you determine that, use a regex to strip the remaining commas (after you convert the "CENTS" comma to a decimal of course) ... Now you have a normal DEC number to play with.

Use this to find the last comma in your string ... strrpos

Use this to replace the commas preg_replace

Here is a helpful regex website .. regexlib

//Finding the last comma

$yourCommaPos = strrpos($myString, ',');
if ($yourCommaPos == strlen($myString) - 2) {
 //Comma is foreign currency decimal
 // Replace with '.'
} else {
 //Not foreign Currency so...
 //Strip Commas
 preg_replace(',', '', $myString);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文