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

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

当前回答

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

dd('0.3454545' + 0)

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

其他回答

您不必选择是将字符串转换为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将在限制范围内为您提供

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

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

在一次编程面试中,我遇到了这样一个问题:“假设你正在编写一个内置函数,用PHP将整数转换为字符串,你会如何编写该函数”。这里有一个解决方案。

$nums = ["0","1","2","3","4","5","6","7","8","9"];
$int = 15939; 
$string = ""; 
while ($int) { 
    $string .= $nums[$int % 10]; 
    $int = (int)($int / 10); 
} 
$result = strrev($string);

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

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

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

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';