php 如何检查输入的值是否为货币

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4982291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:25:54  来源:igfitidea点击:

How to check if an entered value is currency

phpregex

提问by Kareem Nour Emam

How to check if an entered value is currency.Preferably by regular expression or php function.

如何检查输入的值是否为货币。最好通过正则表达式或php函数。

(values like 1550.50, 1500or 100.75)

(值如1550.50,1500100.75

回答by Tim Pietzcker

I guess what you really want is a way to tell anynumber from a number that makes senseas a currency value. So 1.04e-7probably shouldn't match, and neither should 1.234or 12.3, even though all are of course numeric.

我想您真正想要的是一种从作为货币价值的数字分辨出任何数字的方法。所以可能不应该匹配,也不应该或,即使所有当然都是数字。1.04e-71.23412.3

Finally, you'd have to expect thousands separators like 1,234.56(which, like the decimal point, might also vary between locales). So, assuming that you only ever want to check currency values using the dot as decimal separator and the comma as an optional thousands separator, try this:

最后,您必须期望有数千个分隔符1,234.56(与小数点一样,也可能因区域设置而异)。因此,假设您只想使用点作为小数分隔符和逗号作为可选的千位分隔符来检查货币值,请尝试以下操作:

/\b\d{1,3}(?:,?\d{3})*(?:\.\d{2})?\b/

Explanation:

解释:

\b      # word boundary assertion
\d{1,3} # 1-3 digits
(?:     # followed by this group...
 ,?     # an optional comma
 \d{3}  # exactly three digits
)*      # ...any number of times
(?:     # followed by this group...
 \.     # a literal dot
 \d{2}  # exactly two digits
)?      # ...zero or one times
\b      # word boundary assertion

回答by Marco Demaio

I use this:

我用这个:

function isCurrency($number)
{
  return preg_match("/^-?[0-9]+(?:\.[0-9]{1,2})?$/", $number);
}

//usage examples
echo (isCurrency("10.36") ? "TRUE" : "FALSE");
echo (isCurrency(10.3) ? "TRUE" : "FALSE");

Beware of:

提防:

  1. this function accepts also negative currency values, if you don't want to accept them remove the -?that you find at the beginning of the preg_match

  2. this function returns TRUEalso for values like 13.7(only one decimal), if you want the decimal to be always two than replace {1,2}with {2}(but prior doing this read point 3 below)

  3. this function returns TRUEalso for values like 0000.78(more than one leading zero), but usually this kind of function is needed to filter value submitted by forms before inserting them into DB fields of type DECIMAL(n.2). When inserting in these kind of fields MySQL accepts both 0000.78and 13.7as valid values in query, and auto converts them into 0.78and 13.70

  1. 此函数也接受负货币值,如果您不想接受它们,请删除-?您在开头找到的preg_match

  2. 如果您希望小数始终为两位而不是替换为(但在执行下面的读取点 3 之前),则此函数TRUE也会返回诸如13.7(仅一位小数)之类的值{1,2}{2}

  3. 这个函数TRUE也返回像0000.78(超过一个前导零)这样的值,但通常需要这种函数来过滤表单提交的值,然后再将它们插入到类型的数据库字段中DECIMAL(n.2)。当插入这些类型的字段时,MySQL 接受0000.7813.7作为查询中的有效值,并自动将它们转换为0.7813.70

回答by d-_-b

You can't be sure. The user might be thinking of chickens. You need to check if the user entered a float. Have a look at preg_match: http://jp2.php.net/manual/en/function.preg-match.php

你不能确定。用户可能会想到鸡。您需要检查用户是否输入了浮点数。看看 preg_match:http: //jp2.php.net/manual/en/function.preg-match.php

You also need to ask yourself if you want to try to work with what the user entered, or if you want to reject it and only accept an exact format.

您还需要问自己是否要尝试使用用户输入的内容,或者是否要拒绝它而只接受确切的格式。

回答by Edward

I quickly spun up a function for checking if a string or int is a valid price and if not, converting it. The final output is always going to be a string with two digits after the decimal, like 1000.00.

我很快就创建了一个函数来检查一个字符串或整数是否是一个有效的价格,如果不是,则转换它。最终输出始终是一个小数点后有两位数字的字符串,例如1000.00.

It removes minus/negative signs, commas, spaces, and dollar signs. The only except is when if the string contains any characters like letters that would set is_numeric()to false.

它删除减号/负号、逗号、空格和美元符号。唯一的例外是当字符串包含任何字符(如将设置is_numeric()为 false 的字母)时。

Here is the function:

这是函数:

function convertToValidPrice($price) {
    $price = str_replace(['-', ',', '$', ' '], '', $price);
    if(!is_numeric($price)) {
        $price = null;
    } else {
        if(strpos($price, '.') !== false) {
            $dollarExplode = explode('.', $price);
            $dollar = $dollarExplode[0];
            $cents = $dollarExplode[1];
            if(strlen($cents) === 0) {
                $cents = '00';
            } elseif(strlen($cents) === 1) {
                $cents = $cents.'0';
            } elseif(strlen($cents) > 2) {
                $cents = substr($cents, 0, 2);
            }
            $price = $dollar.'.'.$cents;
        } else {
            $cents = '00';
            $price = $price.'.'.$cents;
        }
    }

    return $price;
}

And here is to test it:

这里是测试它:

var_dump(convertToValidPrice('100'));          // 100.00
var_dump(convertToValidPrice('-100'));         // 100.00
var_dump(convertToValidPrice(100));            // 100.00
var_dump(convertToValidPrice('0'));         // 100.00
var_dump(convertToValidPrice('100.98'));       // 100.98
var_dump(convertToValidPrice('100.9'));        // 100.90
var_dump(convertToValidPrice('100.'));         // 100.00
var_dump(convertToValidPrice('1,00.98'));      // 100.98
var_dump(convertToValidPrice('1,000.98'));     // 1000.98
var_dump(convertToValidPrice('100.98829382')); // 100.98
var_dump(convertToValidPrice('abc'));          // null