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

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

当前回答

function convert_to_number($number) {
    return is_numeric($number) ? ($number + 0) : FALSE;
}

其他回答

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

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

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

如果你想要一个字符串的数值,但因为不确定而不想将其转换为float/int,这个技巧会将其转换成正确的类型:

function get_numeric($val) {
  if (is_numeric($val)) {
    return $val + 0;
  }
  return 0;
}

Example:
<?php
get_numeric('3'); // int(3)
get_numeric('1.2'); // float(1.2)
get_numeric('3.0'); // float(3)
?>

资料来源:https://www.php.net/manual/en/function.is-numeric.php#107326

如果您希望为$value=“0.4”获取浮点值,但为$value=“4”获取int值,则可以编写:

$number = ($value == (int) $value) ? (int) $value : (float) $value;

它有点脏,但很管用。

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

所有建议都会丢失数字类型。

在我看来,这是一个最佳实践:

function str2num($s){
// Returns a num or FALSE
    $return_value =  !is_numeric($s) ? false :               (intval($s)==floatval($s)) ? intval($s) :floatval($s);
    print "\nret=$return_value type=".gettype($return_value)."\n";
}