PHP에서 문자열을 숫자로 어떻게 변환합니까?
나는 값, 이러한 유형의 변환 할 '3'
, '2.34'
, '0.234343'
숫자로 등. JavaScript에서는을 사용할 수 Number()
있지만 PHP에서 사용할 수있는 유사한 방법이 있습니까?
Input Output
'2' 2
'2.34' 2.34
'0.3454545' 0.3454545
PHP는 대부분의 상황에서 유형을 강제하므로 일반적으로이 작업을 수행 할 필요가 없습니다. 유형을 명시 적으로 변환하려는 경우에는 다음과 같이 캐스트 하십시오.
$num = "3.14";
$int = (int)$num;
$float = (float)$num;
이를 수행하는 몇 가지 방법이 있습니다.
문자열을 숫자 기본 데이터 유형으로 캐스트하십시오.
$num = (int) "10"; $num = (double) "10.12"; // same as (float) "10.12";
문자열에 대해 수학 연산을 수행합니다.
$num = "10" + 1; $num = floor("10.1");
사용
intval()
또는floatval()
:$num = intval("10"); $num = floatval("10.1");
사용
settype()
.
어떤 (느슨하게 입력 된) 언어에서든지 0을 추가하여 항상 문자열을 숫자로 캐스트 할 수 있습니다.
그러나이 변수를 사용할 때 PHP가 자동으로 수행하고 출력시 문자열로 형변환되므로 이에 대해서는 거의 의미가 없습니다.
float로 캐스팅 한 후에는 float 숫자의 특성으로 인해 예기치 않게 변경 될 수 있으므로 점으로 된 숫자를 문자열로 유지하는 것이 좋습니다.
문제를 방지하려면 intval($var)
. 몇 가지 예 :
<?php
echo intval(42); // 42
echo intval(4.2); // 4
echo intval('42'); // 42
echo intval('+42'); // 42
echo intval('-42'); // -42
echo intval(042); // 34 (octal as starts with zero)
echo intval('042'); // 42
echo intval(1e10); // 1410065408
echo intval('1e10'); // 1
echo intval(0x1A); // 26 (hex as starts with 0x)
echo intval(42000000); // 42000000
echo intval(420000000000000000000); // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8); // 42
echo intval('42', 8); // 34
echo intval(array()); // 0
echo intval(array('foo', 'bar')); // 1
?>
당신이 사용할 수있는:
(int)(your value);
또는 다음을 사용할 수 있습니다.
intval(string)
에 대한 float를 얻고 $value = '0.4'
싶지만 int에 대해서는 다음 $value = '4'
과 같이 작성할 수 있습니다.
$number = ($value == (int) $value) ? (int) $value : (float) $value;
조금 더럽지 만 작동합니다.
항상 0을 추가 할 수 있습니다!
Input Output
'2' + 0 2 (int)
'2.34' + 0 2.34 (float)
'0.3454545' + 0 0.3454545 (float)
대신 변환할지 여부를 선택할 필요없이 string
에 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;
In PHP you can use intval(string) or floatval(string)
functions to convert strings to numbers.
Just a little note to the answers that can be useful and safer in some cases. You may want to check if the string actually contains a valid numeric value first and only then convert it to a numeric type (for example if you have to manipulate data coming from a db that converts ints to strings). You can use is_numeric()
and then floatval()
:
$a = "whatever"; // any variable
if (is_numeric($a))
var_dump(floatval($a)); // type is float
else
var_dump($a); // any type
Yes, there is a similar method in PHP, but it is so little known that you will rarely hear about it. It is an arithmetic operator called "identity", as described here:
To convert a numeric string to a number, do as follows:
$a = +$a;
Here is the function that achieves what you are looking for. First we check if the value can be understood as a number, if so we turn it into an int and a float. If the int and float are the same (e.g., 5 == 5.0) then we return the int value. If the int and float are not the same (e.g., 5 != 5.3) then we assume you need the precision of the float and return that value. If the value isn't numeric we throw a warning and return 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;
}
}
I've found that in JavaScript a simple way to convert a string to a number is to multiply it by 1. It resolves the concatenation problem, because the "+" symbol has multiple uses in JavaScript, while the "*" symbol is purely for mathematical multiplication.
Based on what I've seen here regarding PHP automatically being willing to interpret a digit-containing string as a number (and the comments about adding, since in PHP the "+" is purely for mathematical addition), this multiply trick works just fine for PHP, also.
I have tested it, and it does work... Although depending on how you acquired the string, you might want to apply the trim() function to it, before multiplying by 1.
Here is a function I wrote to simplify things for myself:
It also returns shorthand versions of boolean, integer, double and real.
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;
}
}
Calling type with parseNumeric set to true will convert numeric strings before checking type.
Thus:
type("5", true) will return int
type("3.7", true) will return float
type("500") will return string
Just be careful since this is a kind of false checking method and your actual variable will still be a string. You will need to convert the actual variable to the correct type if needed. I just needed it to check if the database should load an item id or alias, thus not having any unexpected effects since it will be parsed as string at run time anyway.
Edit
If you would like to detect if objects are functions add this case to the switch:
case 'object': return is_callable($mixed)?'function':'object';
In addition to Boykodev's answer I suggest this:
Input Output
'2' * 1 2 (int)
'2.34' * 1 2.34 (float)
'0.3454545' * 1 0.3454545 (float)
Simply you can write like this:
<?php
$data = ["1","2","3","4","5"];
echo json_encode($data, JSON_NUMERIC_CHECK);
?>
$a = "10";
$b = (int)$a;
You can use this to convert a string to an int in PHP.
You can use:
((int) $var) ( but in big number it return 2147483647 :-) )
But the best solution is to use:
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;
You can change the data type as follows
$number = "1.234";
echo gettype ($number) . "\n"; //Returns string
settype($number , "float");
echo gettype ($number) . "\n"; //Returns float
For historical reasons "double" is returned in case of a float.
PHP will do it for you within limits
<?php
$str = "3.148";
$num = $str;
printf("%f\n", $num);
?>
All suggestions lose the numeric type.
This seems to me a best practice:
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";
}
There is a way:
$value = json_decode(json_encode($value, JSON_NUMERIC_CHECK|JSON_PRESERVE_ZERO_FRACTION|JSON_UNESCAPED_SLASHES), true);
Using is_*
won't work, since the variable
is a: string
.
Using the combination of json_encode()
and then json_decode()
it's converted to it's "true" form. If it's a true string
then it would output wrong.
$num = "Me";
$int = (int)$num;
$float = (float)$num;
var_dump($num, $int, $float);
Will output: string(2) "Me" int(0) float(0)
I got the question "say you were writing the built in function for casting an integer to a string in PHP, how would you write that function" in a programming interview. Here's a solution.
$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);
I've been reading through answers and didn't see anybody mention the biggest caveat in PHP's number conversion.
The most upvoted answer suggests doing the following:
$str = "3.14"
$intstr = (int)$str // now it's a number equal to 3
That's brilliant. PHP does direct casting. But what if we did the following?
$str = "3.14is_trash"
$intstr = (int)$str
Does PHP consider such conversions valid?
Apparently yes.
PHP reads the string until it finds first non-numerical character for the required type. Meaning that for integers, numerical characters are [0-9]. As a result, it reads 3
, since it's in [0-9] character range, it continues reading. Reads .
and stops there since it's not in [0-9] range.
Same would happen if you were to cast to float or double. PHP would read 3
, then .
, then 1
, then 4
, and would stop at i
since it's not valid float numeric character.
As a result, "million" >= 1000000
evaluates to false, but "1000000million" >= 1000000
evaluates to true
.
See also:
https://www.php.net/manual/en/language.operators.comparison.php how conversions are done while comparing
https://www.php.net/manual/en/language.types.string.php#language.types.string.conversion how strings are converted to respective numbers
Different approach:
- Push it all into an array / associative array.
json_encode($your_array, JSON_NUMERIC_CHECK);
optionally decode it back- ?
- Profit!
참고URL : https://stackoverflow.com/questions/8529656/how-do-i-convert-a-string-to-a-number-in-php
'developer tip' 카테고리의 다른 글
git 커밋이 어떤 브랜치에서 왔는지 찾기 (0) | 2020.10.03 |
---|---|
localStorage에 어레이를 어떻게 저장합니까? (0) | 2020.10.03 |
jquery를 사용하여 확인란을 선택 / 선택 취소 하시겠습니까? (0) | 2020.10.03 |
Java assert 키워드의 기능은 무엇이며 언제 사용해야합니까? (0) | 2020.10.03 |
ConcurrentHashMap과 Collections.synchronizedMap (Map)의 차이점은 무엇입니까? (0) | 2020.10.03 |