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

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

当前回答

您不必选择是将字符串转换为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);
?>

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

在任何(松散类型)语言中,您都可以通过在数字上加一个零来将字符串转换为数字。

然而,这没有什么意义,因为PHP将在使用此变量时自动执行,并且在输出时无论如何都将转换为字符串。

请注意,您可能希望将虚线保留为字符串,因为在强制转换为浮点数后,由于浮点数的性质,它可能会发生不可预测的变化。

我发现在JavaScript中,将字符串转换为数字的简单方法是将其乘以1。它解决了连接问题,因为“+”符号在JavaScript中有多种用途,而“*”符号纯粹用于数学乘法。

基于我在这里看到的关于PHP自动愿意将包含字符串的数字解释为数字(以及关于加法的注释,因为在PHP中,“+”纯粹是用于数学加法)的内容,这种乘法技巧也适用于PHP。

我已经测试过了,它确实有效。。。尽管取决于获取字符串的方式,您可能需要在乘以1之前对其应用trim()函数。

这是实现您所需功能的函数。首先,我们检查该值是否可以理解为数字,如果可以,我们将其转换为int和float。如果int和float相同(例如,5==5.0),则返回int值。如果int和float不相同(例如,5!=5.3),那么我们假设您需要float的精度并返回该值。如果值不是数字,我们将抛出警告并返回null。

function toNumber($val) {
    if (is_numeric($val)) {
        $int = (int)$val;
        $float = (float)$val;

        $val = ($int == $float) ? $int : $float;
        return $val;
    } else {
        trigger_error("Cannot cast $val to a number", E_USER_WARNING);
        return null;
    }
}