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

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

当前回答

如果你事先不知道你有一个浮点数还是一个整数,如果字符串可能包含特殊字符(如空格、欧元等),并且如果它可以包含多于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;
}

其他回答

如果你想要一个字符串的数值,但因为不确定而不想将其转换为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

您可以使用:

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

在某些情况下,只需注意一些有用且安全的答案。您可能需要先检查字符串是否包含有效的数值,然后才能将其转换为数值类型(例如,如果您必须处理来自将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
$a = "10";

$b = (int)$a;

您可以使用它在PHP中将字符串转换为int。

除了Boykodev的回答,我还建议:

Input             Output
'2' * 1           2 (int)
'2.34' * 1        2.34 (float)
'0.3454545' * 1   0.3454545 (float)