我想将这些类型的值“3”、“2.34”、“0.234343”等转换为数字。在JavaScript中,我们可以使用Number(),但在PHP中有没有类似的方法?
Input Output
'2' 2
'2.34' 2.34
'0.3454545' 0.3454545
我想将这些类型的值“3”、“2.34”、“0.234343”等转换为数字。在JavaScript中,我们可以使用Number(),但在PHP中有没有类似的方法?
Input Output
'2' 2
'2.34' 2.34
'0.3454545' 0.3454545
当前回答
使用一元运算符(+)。例如:
$n1 = +'7';
$n2 = '2.34';
$n2 = +$n1;
var_dump($n1):int(7)var_dump($n2):浮点(2.34)
其他回答
$a = "10";
$b = (int)$a;
您可以使用它在PHP中将字符串转换为int。
如果您希望为$value=“0.4”获取浮点值,但为$value=“4”获取int值,则可以编写:
$number = ($value == (int) $value) ? (int) $value : (float) $value;
它有点脏,但很管用。
如果你事先不知道你有一个浮点数还是一个整数,如果字符串可能包含特殊字符(如空格、欧元等),并且如果它可以包含多于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会强制您使用类型。对于确实要显式转换类型的情况,请将其强制转换为:
$num = "3.14";
$int = (int)$num;
$float = (float)$num;
在PHP中,您可以使用intval(string)或floatval(字符串)函数将字符串转换为数字。