(PHP 4, PHP 5)
is_float — 检测变量是否是浮点型
如果 var
是 float 则返回 TRUE
,否则返回 FALSE
。
Note:
若想测试一个变量是否是数字或数字字符串(如表单输入,它们通常为字符串),必须使用 is_numeric()。
参见 is_bool()、 is_int()、 is_integer()、 is_numeric()、 is_string()、 is_array() 和 is_object()。
yo_llo at gmail dot com (2013-01-21 17:33:40)
To check if a variable is a floating string type:
<?php
$var = "1.2";
if (is_numeric ($var) && fmod ((float) $var, 1) !== 0) echo "float";
?>
KIVagant at gmail dot com (2012-08-21 12:04:30)
Yet another regular expression for float in real life:
<?php
function isTrueFloat($val)
{
$pattern = '/^[-+]?(((\\\\d+)\\\\.?(\\\\d+)?)|\\\\.\\\\d+)([eE]?[+-]?\\\\d+)?$/';
return (!is_bool($val) && (is_float($val) || preg_match($pattern, trim($val))));
}
?>
// Matches:
1, -1, 1.0, -1.0, '1', '-1', '1.0', '-1.0', '2.1', '0', 0, ' 0 ', ' 0.1 ', ' -0.0 ', -0.0, 3., '-3.', '.27', .27, '-0', '+4', '1e2', '+1353.0316547', '13213.032468e-13465', '-8E+3', '-1354.98879e+37436'
// Non-matches:
false, true, '', '-', '.a', '-1.a', '.a', '.', '-.', '1+', '1.3+', 'a1', 'e.e', '-e-4', 'e2', '8e', '3,25'
Mitch (2012-06-12 20:27:13)
Another RegEx for matching floats:
/^[+-]?(\d*\.\d+([eE]?[+-]?\d+)?|\d+[eE][+-]?\d+)$/
Matches:
1e2
+1353.0316547
13213.032468e-13465
-8E+3
-1354.98879e+37436
Non-matches:
8
e2
-e-4
E
asdf.safd
8e
Enjoy.
Boylett (2008-09-20 09:29:40)
If you want to test whether a string is containing a float, rather than if a variable is a float, you can use this simple little function:
function isfloat($f) return ($f == (string)(float)$f);
ckelley at the ca - cycleworks dot com (2008-07-14 15:39:58)
Personally, I use an implicit cast:
if( is_float($value+1) ){
$value=sprintf("%.2f",$value);
}
Which turns 22.0000000 query result into 22.00 for display to users.
kshegunov at gmail dot com (2008-03-31 13:32:24)
As celelibi at gmail dot com stated, is_float checks ONLY the type of the variable not the data it holds!
If you want to check if string represent a floating point value use the following regular expression and not is_float(),
or poorly written custom functions.
/^[+-]?(([0-9]+)|([0-9]*\.[0-9]+|[0-9]+\.[0-9]*)|
(([0-9]+|([0-9]*\.[0-9]+|[0-9]+\.[0-9]*))[eE][+-]?[0-9]+))$/
celelibi at gmail dot com (2008-03-03 08:31:25)
Unlike others comment may let you think, this function tests *only* the type of the variable. It does not perform any other test.
If you want to check if a string represents a valid float value, please use is_numeric instead.
phper (2006-01-25 12:08:36)
A better way to check for a certain number of decimal places is to use :
$num_dec_places = 2;
number_format($value,$num_dec_places);
kirti dot contact at gmail dot com (2005-10-18 23:18:07)
To check a float only should contain certain number of decimal places, I have used this simple function below
<?
function is_deccount($number,$decimal=2){
$m_factor=pow(10,$decimal);
if((int)($number*$m_factor)==$number*$m_factor)
return true;
else
return false;
}
?>