我想将这些类型的值“3”、“2.34”、“0.234343”等转换为数字。在JavaScript中,我们可以使用Number(),但在PHP中有没有类似的方法?
Input Output
'2' 2
'2.34' 2.34
'0.3454545' 0.3454545
我想将这些类型的值“3”、“2.34”、“0.234343”等转换为数字。在JavaScript中,我们可以使用Number(),但在PHP中有没有类似的方法?
Input Output
'2' 2
'2.34' 2.34
'0.3454545' 0.3454545
当前回答
有一种方法:
$value = json_decode(json_encode($value, JSON_NUMERIC_CHECK|JSON_PRESERVE_ZERO_FRACTION|JSON_UNESCAPED_SLASHES), true);
使用is_*不起作用,因为变量是:string。
使用json_encode()和json_edecode()的组合将其转换为“真”形式。如果它是真字符串,则输出错误。
$num = "Me";
$int = (int)$num;
$float = (float)$num;
var_dump($num, $int, $float);
将输出:string(2)“Me”int(0)float(0)
其他回答
$a = "10";
$b = (int)$a;
您可以使用它在PHP中将字符串转换为int。
可以按如下方式更改数据类型
$number = "1.234";
echo gettype ($number) . "\n"; //Returns string
settype($number , "float");
echo gettype ($number) . "\n"; //Returns float
由于历史原因,浮动时返回“double”。
PHP文档
如果你事先不知道你有一个浮点数还是一个整数,如果字符串可能包含特殊字符(如空格、欧元等),并且如果它可以包含多于1个点或逗号,您可以使用此功能:
// This function strip spaces and other characters from a string and return a number.
// It works for integer and float.
// It expect decimal delimiter to be either a '.' or ','
// Note: everything after an eventual 2nd decimal delimiter will be removed.
function stringToNumber($string) {
// return 0 if the string contains no number at all or is not a string:
if (!is_string($string) || !preg_match('/\d/', $string)) {
return 0;
}
// Replace all ',' with '.':
$workingString = str_replace(',', '.', $string);
// Keep only number and '.':
$workingString = preg_replace("/[^0-9.]+/", "", $workingString);
// Split the integer part and the decimal part,
// (and eventually a third part if there are more
// than 1 decimal delimiter in the string):
$explodedString = explode('.', $workingString, 3);
if ($explodedString[0] === '') {
// No number was present before the first decimal delimiter,
// so we assume it was meant to be a 0:
$explodedString[0] = '0';
}
if (sizeof($explodedString) === 1) {
// No decimal delimiter was present in the string,
// create a string representing an integer:
$workingString = $explodedString[0];
} else {
// A decimal delimiter was present,
// create a string representing a float:
$workingString = $explodedString[0] . '.' . $explodedString[1];
}
// Create a number from this now non-ambiguous string:
$number = $workingString * 1;
return $number;
}
有几种方法可以做到这一点:
将字符串强制转换为数字基元数据类型:$num=(int)“10”;$num=(double)“10.12”;//与(浮动)“10.12”相同;对字符串执行数学运算:$num=“10”+1;$num=地板(“10.1”);使用intval()或floatval():$num=intval(“10”);$num=浮动值(“10.1”);使用settype()。
您可以使用:
((int) $var) ( but in big number it return 2147483647 :-) )
但最好的解决方案是使用:
if (is_numeric($var))
$var = (isset($var)) ? $var : 0;
else
$var = 0;
Or
if (is_numeric($var))
$var = (trim($var) == '') ? 0 : $var;
else
$var = 0;