检查数字是否为小数

发布于 2024-11-25 06:54:18 字数 69 浏览 1 评论 0原文

如果用户输入了十进制数(美国方式,带小数点:X.XXX),我需要检查 PHP

是否有可靠的方法来执行此操作?

I need to check in PHP if user entered a decimal number (US way, with decimal point: X.XXX)

Any reliable way to do this?

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

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

发布评论

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

评论(19

眼趣 2024-12-02 06:54:18

您可以从 is_float 获得大部分您想要的内容,但是如果您 < em>真的需要知道它是否有小数,上面的函数并不是很远(尽管是错误的语言):

function is_decimal( $val )
{
    return is_numeric( $val ) && floor( $val ) != $val;
}

You can get most of what you want from is_float, but if you really need to know whether it has a decimal in it, your function above isn't terribly far (albeit the wrong language):

function is_decimal( $val )
{
    return is_numeric( $val ) && floor( $val ) != $val;
}
凉风有信 2024-12-02 06:54:18

如果您希望“10.00”返回 true,请检查 Night Owl 的答案

如果您想知道小数是否有值,您可以使用此答案。

适用于所有类型(int、float、string)

if(fmod($val, 1) !== 0.00){
    // your code if its decimals has a value
} else {
    // your code if the decimals are .00, or is an integer
}

示例:

(fmod(1.00,    1) !== 0.00)    // returns false
(fmod(2,       1) !== 0.00)    // returns false
(fmod(3.01,    1) !== 0.00)    // returns true
(fmod(4.33333, 1) !== 0.00)    // returns true
(fmod(5.00000, 1) !== 0.00)    // returns false
(fmod('6.50',  1) !== 0.00)    // returns true

说明:

fmod 返回参数除法的浮点余数(模),(因此是 (!== 0.00))

模运算符 - 为什么不使用模数 操作员?例如 ($val % 1 != 0)

来自 PHP 文档

模数操作数在处理之前会转换为整数(通过去除小数部分)。

这将有效地破坏运算目的,在其他语言(如 javascript)中,您可以使用模运算符

if you want "10.00" to return true check Night Owl's answer

If you want to know if the decimals has a value you can use this answer.

Works with all kind of types (int, float, string)

if(fmod($val, 1) !== 0.00){
    // your code if its decimals has a value
} else {
    // your code if the decimals are .00, or is an integer
}

Examples:

(fmod(1.00,    1) !== 0.00)    // returns false
(fmod(2,       1) !== 0.00)    // returns false
(fmod(3.01,    1) !== 0.00)    // returns true
(fmod(4.33333, 1) !== 0.00)    // returns true
(fmod(5.00000, 1) !== 0.00)    // returns false
(fmod('6.50',  1) !== 0.00)    // returns true

Explanation:

fmod returns the floating point remainder (modulo) of the division of the arguments, (hence the (!== 0.00))

Modulus operator - why not use the modulus operator? E.g. ($val % 1 != 0)

From the PHP docs:

Operands of modulus are converted to integers (by stripping the decimal part) before processing.

Which will effectively destroys the op purpose, in other languages like javascript you can use the modulus operator

待天淡蓝洁白时 2024-12-02 06:54:18

如果您需要知道的是变量中是否存在小数点,那么这将完成工作...

function containsDecimal( $value ) {
    if ( strpos( $value, "." ) !== false ) {
        return true;
    }
    return false;
}

这不是一个非常优雅的解决方案,但它适用于字符串和浮点数。

确保在 strpos 测试中使用 !== 而不是 != ,否则您将得到不正确的结果。

If all you need to know is whether a decimal point exists in a variable then this will get the job done...

function containsDecimal( $value ) {
    if ( strpos( $value, "." ) !== false ) {
        return true;
    }
    return false;
}

This isn't a very elegant solution but it works with strings and floats.

Make sure to use !== and not != in the strpos test or you will get incorrect results.

心是晴朗的。 2024-12-02 06:54:18

解决此问题的另一种方法: preg_match('/^\d+\.\d+$/',$number); :)

another way to solve this: preg_match('/^\d+\.\d+$/',$number); :)

喜爱皱眉﹌ 2024-12-02 06:54:18

您发布的功能不是 PHP。

看看 is_float [docs]< /sup>

编辑:我错过了“用户输入的值”部分。在这种情况下,您实际上可以使用正则表达式:

^\d+\.\d+$

The function you posted is just not PHP.

Have a look at is_float [docs].

Edit: I missed the "user entered value" part. In this case you can actually use a regular expression:

^\d+\.\d+$
染墨丶若流云 2024-12-02 06:54:18

我收到一个字符串,想知道它是否是小数。我最终得到了这个:

function isDecimal($value) 
{
     return ((float) $value !== floor($value));
}

我运行了一系列测试,包括零两边的小数和非小数,它似乎有效。

I was passed a string, and wanted to know if it was a decimal or not. I ended up with this:

function isDecimal($value) 
{
     return ((float) $value !== floor($value));
}

I ran a bunch of test including decimals and non-decimals on both sides of zero, and it seemed to work.

大海や 2024-12-02 06:54:18

is_numeric 对于小数和整数返回 true。因此,如果您的用户懒惰地输入 1 而不是 1.00,它仍然会返回 true

echo is_numeric(1); // true
echo is_numeric(1.00); // true

您可能希望使用 PHP 将整数转换为小数,或者让您的数据库为您做这件事。

is_numeric returns true for decimals and integers. So if your user lazily enters 1 instead of 1.00 it will still return true:

echo is_numeric(1); // true
echo is_numeric(1.00); // true

You may wish to convert the integer to a decimal with PHP, or let your database do it for you.

踏雪无痕 2024-12-02 06:54:18

我无法发表评论,但我有这种有趣的行为。
(在 php 在线测试网站上的 v. 7.3.19 上测试)

如果将 50 乘以 1.1 fmod 会得到与预期不同的结果。
如果你做到 1.2 或 1.3 就可以了,如果你做到了其他数字(如 60 或 40)也可以。

$price = 50;
$price = $price * 1.1; 

if(strpos($price,".") !== false){
    echo "decimal";
}else{
    echo "not a decimal";
}

echo '<br />';

if(fmod($price, 1) !== 0.00){
    //echo fmod($price, 1);
    echo "decimal";
} else {
    echo "not a decimal";
}//end if

I can't comment, but I have this interesting behaviour.
(tested on v. 7.3.19 on a website for php testing online)

If you multiply 50 by 1.1 fmod gives different results than expected.
If you do by 1.2 or 1.3 it's fine, if you do another number (like 60 or 40) is also fine.

$price = 50;
$price = $price * 1.1; 

if(strpos($price,".") !== false){
    echo "decimal";
}else{
    echo "not a decimal";
}

echo '<br />';

if(fmod($price, 1) !== 0.00){
    //echo fmod($price, 1);
    echo "decimal";
} else {
    echo "not a decimal";
}//end if
凉世弥音 2024-12-02 06:54:18

这是通过用户输入处理此问题的更容忍的方式。此正则表达式将匹配“100”或“100.1”,但不允许负数。

/^(\d+)(\.\d+)?$/

This is a more tolerate way to handle this with user input. This regex will match both "100" or "100.1" but doesn't allow for negative numbers.

/^(\d+)(\.\d+)?$/
诺曦 2024-12-02 06:54:18
   // if numeric 

if (is_numeric($field)) {
        $whole = floor($field);
        $fraction = $field - $whole;

        // if decimal            
        if ($fraction > 0)
            // do sth
        else
        // if integer
            // do sth 
}
else

   // if non-numeric
   // do sth
   // if numeric 

if (is_numeric($field)) {
        $whole = floor($field);
        $fraction = $field - $whole;

        // if decimal            
        if ($fraction > 0)
            // do sth
        else
        // if integer
            // do sth 
}
else

   // if non-numeric
   // do sth
ぃ双果 2024-12-02 06:54:18

我用这个:

function is_decimal ($price){
  $value= trim($price); // trim space keys
  $value= is_numeric($value); // validate numeric and numeric string, e.g., 12.00, 1e00, 123; but not -123
  $value= preg_match('/^\d$/', $value); // only allow any digit e.g., 0,1,2,3,4,5,6,7,8,9. This will eliminate the numeric string, e.g., 1e00
  $value= round($value, 2); // to a specified number of decimal places.e.g., 1.12345=> 1.12

  return $value;
}

i use this:

function is_decimal ($price){
  $value= trim($price); // trim space keys
  $value= is_numeric($value); // validate numeric and numeric string, e.g., 12.00, 1e00, 123; but not -123
  $value= preg_match('/^\d$/', $value); // only allow any digit e.g., 0,1,2,3,4,5,6,7,8,9. This will eliminate the numeric string, e.g., 1e00
  $value= round($value, 2); // to a specified number of decimal places.e.g., 1.12345=> 1.12

  return $value;
}
猫卆 2024-12-02 06:54:18
$lat = '-25.3654';

if(preg_match('/./',$lat)) {
    echo "\nYes its a decimal value\n";
}
else{
    echo 'No its not a decimal value';
}
$lat = '-25.3654';

if(preg_match('/./',$lat)) {
    echo "\nYes its a decimal value\n";
}
else{
    echo 'No its not a decimal value';
}
一张白纸 2024-12-02 06:54:18

完全是一团糟..但是嘿它有效!

$numpart = explode(".", $sumnum); 

if ((exists($numpart[1]) && ($numpart[1] > 0 )){
//    it's a decimal that is greater than zero
} else {
// its not a decimal, or the decimal is zero
}

A total cludge.. but hey it works !

$numpart = explode(".", $sumnum); 

if ((exists($numpart[1]) && ($numpart[1] > 0 )){
//    it's a decimal that is greater than zero
} else {
// its not a decimal, or the decimal is zero
}
背叛残局 2024-12-02 06:54:18

找到发布值的简单方法是整数和浮点数,因此

$postedValue = $this->input->post('value');
if(is_numeric( $postedValue ) && floor( $postedValue ))
{
    echo 'success';
}
else
{
   echo 'unsuccess';
}

如果您给出 10 或 10.5 或 10.0,这将对您有所帮助,如果您定义任何字符或不带点的特殊字符,结果将成功

the easy way to find either posted value is integer and float so this will help you

$postedValue = $this->input->post('value');
if(is_numeric( $postedValue ) && floor( $postedValue ))
{
    echo 'success';
}
else
{
   echo 'unsuccess';
}

if you give 10 or 10.5 or 10.0 the result will be success if you define any character or specail character without dot it will give unsuccess

仙女 2024-12-02 06:54:18

(int)$value != $value 怎么样?
如果 true 则为十进制,如果 false 则不是。

How about (int)$value != $value?
If true it's decimal, if false it's not.

帅气尐潴 2024-12-02 06:54:18

最简单的解决方案是

if(is_float(2.3)){

 echo 'true';

}

Simplest solution is

if(is_float(2.3)){

 echo 'true';

}
不疑不惑不回忆 2024-12-02 06:54:18

如果您正在使用表单验证。然后在这种情况下形成发送字符串。
我使用以下代码来检查表单输入是否为十进制数。
我希望这对你也有用。

function is_decimal($input = '') {

    $alphabets = str_split($input);
    $find = array('0','1','2','3','4','5','6','7','8','9','.'); // Please note: All intiger numbers are decimal. If you want to check numbers without point "." then you can remove '.' from array. 

    foreach ($alphabets as $key => $alphabet) {
        if (!in_array($alphabet, $find)) {
            return false;
        }
    }

    // Check if user has enter "." point more then once.
    if (substr_count($input, ".") > 1) {
        return false;
    }

    return true;
}

If you are working with form validation. Then in this case form send string.
I used following code to check either form input is a decimal number or not.
I hope this will work for you too.

function is_decimal($input = '') {

    $alphabets = str_split($input);
    $find = array('0','1','2','3','4','5','6','7','8','9','.'); // Please note: All intiger numbers are decimal. If you want to check numbers without point "." then you can remove '.' from array. 

    foreach ($alphabets as $key => $alphabet) {
        if (!in_array($alphabet, $find)) {
            return false;
        }
    }

    // Check if user has enter "." point more then once.
    if (substr_count($input, ".") > 1) {
        return false;
    }

    return true;
}
独留℉清风醉 2024-12-02 06:54:18
function is_decimal_value( $a ) {
    $d=0; $i=0;
    $b= str_split(trim($a.""));
    foreach ( $b as $c ) {
        if ( $i==0 && strpos($c,"-") ) continue;
        $i++;
        if ( is_numeric($c) ) continue;
        if ( stripos($c,".") === 0 ) {
            $d++;
            if ( $d > 1 ) return FALSE;
            else continue;
        } else
        return FALSE;
    }
    return TRUE;
}

上述函数的已知问题:

1) 不支持“科学记数法”(1.23E-123)、财政(前导美元或其他)或“尾随 f”(C++ 样式浮点数)或“尾随货币”(美元、英镑等) )

2) 与小数匹配的字符串文件名误报:请注意,例如“10.0”作为文件名无法与小数区分开来,因此如果您尝试从仅字符串,并且文件名与十进制名称匹配且不包含路径,则无法辨别。

function is_decimal_value( $a ) {
    $d=0; $i=0;
    $b= str_split(trim($a.""));
    foreach ( $b as $c ) {
        if ( $i==0 && strpos($c,"-") ) continue;
        $i++;
        if ( is_numeric($c) ) continue;
        if ( stripos($c,".") === 0 ) {
            $d++;
            if ( $d > 1 ) return FALSE;
            else continue;
        } else
        return FALSE;
    }
    return TRUE;
}

Known Issues with the above function:

1) Does not support "scientific notation" (1.23E-123), fiscal (leading $ or other) or "Trailing f" (C++ style floats) or "trailing currency" (USD, GBP etc)

2) False positive on string filenames that match a decimal: Please note that for example "10.0" as a filename cannot be distinguished from the decimal, so if you are attempting to detect a type from a string alone, and a filename matches a decimal name and has no path included, it will be impossible to discern.

ぶ宁プ宁ぶ 2024-12-02 06:54:18

也许也尝试看看这个

!is_int()

Maybe try looking into this as well

!is_int()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文