我想将这些类型的值“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;
}

其他回答

好的,所以我刚刚遇到了这个问题。我的问题是所讨论的数字/字符串具有不同的位数。有些没有小数,有些有几个。所以对我来说,使用int、float、double、intval或floatval都会根据数字给出不同的结果。

所以,简单的解决方案。。。将字符串除以服务器端的1。这会将其强制为一个数字,并保留所有数字,同时修剪不必要的0。它不漂亮,但它有效。

"your number string" / 1

Input       Output
"17"        17
"84.874"    84.874
".00234"    .00234
".123000"   .123
"032"       32

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

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

在一次编程面试中,我遇到了这样一个问题:“假设你正在编写一个内置函数,用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);

你总是可以加零!

Input             Output
'2' + 0           2 (int)
'2.34' + 0        2.34 (float)
'0.3454545' + 0   0.3454545 (float)

有一种方法:

$value = json_decode(json_encode($value, JSON_NUMERIC_CHECK|JSON_PRESERVE_ZERO_FRACTION|JSON_UNESCAPED_SLASHES), true);

使用is_*不起作用,因为变量是:string。

使用json_encode()和json_edecode()的组合将其转换为“真”形式。如果它是真字符串,则输出错误。

$num = "Me";
$int = (int)$num;
$float = (float)$num;

var_dump($num, $int, $float);

将输出:string(2)“Me”int(0)float(0)