我想将这些类型的值“3”、“2.34”、“0.234343”等转换为数字。在JavaScript中,我们可以使用Number(),但在PHP中有没有类似的方法?

Input             Output
'2'               2
'2.34'            2.34
'0.3454545'       0.3454545

当前回答

下面是我为自己编写的一个函数:

它还返回布尔、整数、双精度和实数的简写版本。

function type($mixed, $parseNumeric = false)
{        
    if ($parseNumeric && is_numeric($mixed)) {
        //Set type to relevant numeric format
        $mixed += 0;
    }
    $t = gettype($mixed);
    switch($t) {
        case 'boolean': return 'bool'; //shorthand
        case 'integer': return 'int';  //shorthand
        case 'double': case 'real': return 'float'; //equivalent for all intents and purposes
        default: return $t;
    }
}

调用parseNumeric设置为true的类型将在检查类型之前转换数字字符串。

因此:

type(“5”,true)将返回int

类型(“3.7”,true)将返回float

类型(“500”)将返回字符串

只是要小心,因为这是一种错误检查方法,而实际变量仍然是字符串。如果需要,您需要将实际变量转换为正确的类型。我只需要它来检查数据库是否应该加载项id或别名,这样就不会产生任何意外的影响,因为它在运行时将被解析为字符串。

Edit

如果要检测对象是否为函数,请在开关中添加以下情况:

case 'object': return is_callable($mixed)?'function':'object';

其他回答

您只需将0添加到字符串中,即可将其转换为数字,而不会丢失初始原始值。举个例子:

dd('0.3454545' + 0)

PHP将为您处理转换,或者按照已经建议在字符串前添加+。

在某些情况下,只需注意一些有用且安全的答案。您可能需要先检查字符串是否包含有效的数值,然后才能将其转换为数值类型(例如,如果您必须处理来自将int转换为字符串的数据库的数据)。可以使用is_numeric(),然后使用floatval():

$a = "whatever"; // any variable

if (is_numeric($a)) 
    var_dump(floatval($a)); // type is float
else 
    var_dump($a); // any type

PHP将在限制范围内为您提供

<?php
   $str = "3.148";
   $num = $str;

   printf("%f\n", $num);
?>

在PHP中,您可以使用intval(string)或floatval(字符串)函数将字符串转换为数字。

现在我们正处于一个严格/强类型在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)