我想将这些类型的值“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
当前回答
//Get Only number from string
$string = "123 Hello Zahid";
$res = preg_replace("/[^0-9]/", "", $string);
echo $res."<br>";
//Result 123
其他回答
现在我们正处于一个严格/强类型在PHP中具有更大重要性的时代,我使用json_decode:
$num = json_decode('123');
var_dump($num); // outputs int(123)
$num = json_decode('123.45');
var_dump($num); // outputs float(123.45)
您不必选择是将字符串转换为int还是float,只需在其中添加一个0,PHP就会自动将结果转换为数字类型。
// Being sure the string is actually a number
if (is_numeric($string))
$number = $string + 0;
else // Let the number be 0 if the string is not a number
$number = 0;
在PHP中,您可以使用intval(string)或floatval(字符串)函数将字符串转换为数字。
实现这一目标的多种方式之一是:
$fileDownloadCount = (int) column_data_from_db;
$fileDownloadCount++;
第二行将值递增1。
你总是可以加零!
Input Output
'2' + 0 2 (int)
'2.34' + 0 2.34 (float)
'0.3454545' + 0 0.3454545 (float)