ChatGPT解决这个技术问题 Extra ChatGPT

How do I convert a string to a number in PHP?

I want to convert these types of values, '3', '2.34', '0.234343', etc. to a number. In JavaScript we can use Number(), but is there any similar method available in PHP?

Input             Output
'2'               2
'2.34'            2.34
'0.3454545'       0.3454545
Reader beware: there is no real answer to this question :(
@MatthieuNapoli The answer is that usually Php figures it out for you - one of the perks of a dynamic type system.
With all the chains of uncertainty and 'usually'.
I think what I meant 5 years ago is that there is not a single function that takes the string and returns a proper int or float (you usually don't want a float when an int is given).
@MatthieuNapoli I am glad you clarified your point to mean there is more than one way to skin a cat, rather than there is no way to do this. Casting is very important in database operations, for instance. For example on a parameterized PDO query, there will be a struggle sometimes for the parser to realize it is a number and not a string, and then you end up with a 0 in an integer field because you did not cast the string to an int in the parameter step.

d
deceze

You don't typically need to do this, since PHP will coerce the type for you in most circumstances. For situations where you do want to explicitly convert the type, cast it:

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

here the situation is bit different I want to convert any string(contains only numbers) to a general number. As U may know in javaScript we can use parseInt() to convert string=>int or parseFloat() to convert string=>float. but in general javaScript use Number() to convert string => number. I want a similar method in php?
It was useful for me when I had a month number obtained from a full date string, wich I used to pull a value from a moth names array. Auto casting doesn't happen here because string indexes are valid, but not equivalent.
Depending on the context, it might not be safe to assume that . is the decimal point separator. en.wikipedia.org/wiki/…
@Sara: You can also create a function for converting the string to number by first casting it to integer, then to float and then comparing if both values (integer and float) are equal. If they are, you should return the value as integer, if not, then as a float. Hope you get the idea.
There are times that you need to pass the integer to file system, it is not a good idea to wait for PHP to do the conversion for you.
f
fardjad

There are a few ways to do so:

Cast the strings to numeric primitive data types: $num = (int) "10"; $num = (double) "10.12"; // same as (float) "10.12"; Perform math operations on the strings: $num = "10" + 1; $num = floor("10.1"); Use intval() or floatval(): $num = intval("10"); $num = floatval("10.1"); Use settype().


Note that (double) is just an alias for (float).
@downvoter, I don't know what's wrong with my answer. Note that I posted this before OP edited her question, however this covers the edited question as well ($num = "10" + 1 example).
@ed-ta: pretty sure it would return min/max value instead of 0 if you pass strings to it. I.e. intval("9999999999")==2147483647.
intval is useful because then you can use it in array_map('intval', $arrayOfStrings); which you can't do with casting.
instead of $num = "10" + 1; it's better to use $num = "10" * 1; since that will not change the value (neutral element of multiplication), this is essentially something like toNumber(..) since the final type will be determined by what is needed to convert the string "10" -> (int) 10; "10.1" -> (float) 10.1;
S
SharpC

To avoid problems try intval($var). Some examples:

<?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
?>

IMHO, This is the only correct answer because it is the only one that takes the radix of the numeric string into consideration. All of the responses (even those suggesting a user-defined function) that simply use a type cast will fail if the numeric string has one or more leading zeros, and the string is NOT intended as a number with an octal base.
any idea if I want to convert "12.7896" in to 12.7896?
use floatval() to convert a string to a float. floatval("12.7896") will return 12.7896
Why isn't this the accepted answer? As a PHP outsider I already knew that (int)$my_str wouldn't work since I was dealing specifically with strings liks 01 and 013 that I want to interpret as base 10... So I wanted a way to explicitly provide the base.
P
Peter Mortensen

In whatever (loosely-typed) language you can always cast a string to a number by adding a zero to it.

However, there is very little sense in this as PHP will do it automatically at the time of using this variable, and it will be cast to a string anyway at the time of output.

Note that you may wish to keep dotted numbers as strings, because after casting to float it may be changed unpredictably, due to float numbers' nature.


There are many languages where you cannot cast a string to number by adding a zero, it's usually considered to be an error rather than a valid method of casting :).
honzasp is right, for example in JavaScript typeof('123'+0) gives 'string', because '123'+0 gives '1230'.
Note, in PHP is is recommended that most of the time you use === style comparisons. So if you will be comparing your data it can be very important what type it is stored in.
@oriol in javascript you need to add the number to zero 0+'123' to get 123
@JonathonWisnoski: even more important if you use < or >, as it has different meanings for numbers and strings (i.e. "10" < "2" but 10 > 2).
P
Peter Mortensen

Instead of having to choose whether to convert the string to int or float, you can simply add a 0 to it, and PHP will automatically convert the result to a numeric type.

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

a
aldemarcalazans

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:

Aritmetic Operators

To convert a numeric string to a number, do as follows:

$a = +$a;

Warning: hack detected.
Hi @Greg. Did you click on the link posted here? This is what the developers said about this operator: Conversion of $a to int or float as appropriate. "Conversion", here, cannot be understood as a number-to-number conversion. Why? Because from an exclusive arithmetic point of view, this operator is absolutely useless! Multiplying any number by "+1" (the equivalent of identity function) has absolutely no effect on it. Therefore, I cannot imagine other utility for this operator than the type conversion suggested here.
@Greg - surely this is less of a hack, than most of the other answers. Its a built-in operator, that does exactly what was requested. (Though its probably best to first check is_numeric, so have a place to put code to handle strings that can't convert correctly.)
I understand that it works perfectly to use an arithmetic operator for casting, but it's really easy to miss. I think it's worth a warning.
@Greg - I agree that any time code does something that may be non-obvious to the reader, a comment is worthwhile! (Though it still isn't a hack, as its usage is exactly what the documentation says - though I personally would not have known that, so I would be glad to see a comment there.)
P
Peter Mortensen

If you want get a float for $value = '0.4', but int for $value = '4', you can write:

$number = ($value == (int) $value) ? (int) $value : (float) $value;

It is little bit dirty, but it works.


Possibly less dirty? strpos($val, '.') === false ? intval($val) : floatval($val);
@jchook Possibly dirtier because it's locale-dependent - eg '0,4' instead of '0.4'.
@jchook that breaks on cases like 2.1e2, it has decimal point, but resulting number is integer
@TomášBlatný No it doesn't. That evaluates to false in PHP. You may have confused "float" with "number containing a fractional part"... obviously 210.0 is a float, and in PHP 2.1e2 is a float. Try it. Float has to do with the way the number gets stored in RAM and represented as a numeric literal.
Just use the + identity operator: var_dump(+'0.4', +'4'), gives you a float and an int. php.net/manual/en/language.operators.arithmetic.php
P
Peter Mortensen

You can use:

(int)(your value);

Or you can use:

intval(string)

what if the entered number is '2.3456' how I get 2.3456?
the question is also about floats.
Show me 1 linefrom OP where it says float? before pass comments and down votes look at Original Post.
The example shows floats, it is asking how to convert numeric strings into numeric values (floats and integers)
@MartinvanDriel - It isn't a number. Its a string. The question is how to get either an int or a float result, as appropriate, from a string. Won't is_float return false for a string?
P
Peter Mortensen

In PHP you can use intval(string) or floatval(string) functions to convert strings to numbers.


no I want a common method. which means if its '5' = > it should convert to 5 and if its '2.345' => it should convert to 2.345.
NOT WORKED FOR ME IT CONVERTED "3" TO 0 ZERO.
B
Boykodev

You can always add zero to it!

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

I got this error A non well formed numeric value encountered. any idea?
this is amazing, I never read something like this. great addition to my knowledge
t
taseenb

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

this is the first good answer here. all the above are BS and dangerous since ``` intval("4C775916") => 4``` is going to potentially cause you a nasty bug.
C
CogSciGradStudent

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

k
klodoma

If you want the numerical value of a string and you don't want to convert it to float/int because you're not sure, this trick will convert it to the proper type:

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)
?>

Source: https://www.php.net/manual/en/function.is-numeric.php#107326


get_numeric(010); // int 8 get_numeric('010'); // int 10
P
Peter Mortensen

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)

After thinking about this a little, I can also suggest division by 1 :)
That's a point! :) By the way your solution is much better than all the scientific notations above. Thank you.
this solution solved my problem. In my case, $id_cron = (string)date('YmdHi'); $target_id_cron = $id_cron - 1; instead of $target_id_cron = (int)$id_cron - 1;
I got this error A non well formed numeric value encountered when I want to change string to float $num = '12,24' * 1. Any suggestion?
@AgnesPalit - PHP is anglo-centric. Only recognizes . as decimal separator. Try '12.24' * 1. Though personally I prefer + 0. Addition instead of multiplication.
D
Dragas

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


This is a very good answer. I worked up a bit and wrote some tests for the same tutes.in/php-caveats-int-float-type-conversion
is_numeric($str) helps with this. (As shown in two of the earlier answers - so its not quite accurate that "nobody mentioned the biggest caveat" - though I see no one explained the issue in detail.)
D
Dieter Gribnitz

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

r
rolodef

Only multiply the number by 1 so that the string is converted to type number.

//String value
$string = "5.1"
if(is_numeric($string)){
  $numeric_string = $string*1;
}

Fair enough, but this method (and similar tricks) are already listed in the 24 other answers to this question - I don't see the value in posting it again.
for example stackoverflow.com/a/39832873/5411817 suggested the same trick, 3 years prior.
For the SO platform to work correctly, existing Answers should be upvoted, not duplicated. If there is a typo, either add Comment below the post, or suggest. The SO platform operates in a different way than forums do. But that is part of the value of this platform. Each platform has is strengths. You would add value, in this case, by voting. Or you could comment with additional references/links. On the otherhand, if you had an awesome, game changing explanation, that nobody else offered, you could add an new Answer, while also Upvoting and linking to the previous post.
P
Peter Mortensen

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.


Of course in PHP the multiply trick works exactly the same as the addition trick - with exactly the same caveats - so there isn't any particular reason to ask computer to do a multiplication. Regardless, the cleanest solution is $var = +$str; -- the identity operator.
B
Benni

Late to the party, but here is another approach:

function cast_to_number($input) {
    if(is_float($input) || is_int($input)) {
        return $input;
    }
    if(!is_string($input)) {
        return false;
    }
    if(preg_match('/^-?\d+$/', $input)) {
        return intval($input);
    }
    if(preg_match('/^-?\d+\.\d+$/', $input)) {
        return floatval($input);
    }
    return false;
}

cast_to_number('123.45');       // (float) 123.45
cast_to_number('-123.45');      // (float) -123.45
cast_to_number('123');          // (int) 123
cast_to_number('-123');         // (int) -123
cast_to_number('foo 123 bar');  // false

CAREFUL: This lacks handling of inputs like '.123', '123.', '1.23e6' and possibly others ('0x16', ...).
M
MikelG

Alright so I just ran into this issue. My problem is that the numbers/strings in question having varying numbers of digits. Some have no decimals, others have several. So for me, using int, float, double, intval, or floatval all gave me different results depending on the number.

So, simple solution... divide the string by 1 server-side. This forces it to a number and retains all digits while trimming unnecessary 0's. It's not pretty, but it works.

"your number string" / 1

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

What are the browsers supported with this?
This is done server side
Oh ok, but may I ask can you use this code in all browsers or some browsers?
Umm... as I've said, this code is for server-side. And the question is for PHP, which is server-side execution.
P
Peter Mortensen
$a = "10";

$b = (int)$a;

You can use this to convert a string to an int in PHP.


if the entered number is '7.2345' I can't use (int) then I have to use (float). What I need is a general solution.
You can always use double or float.
P
Peter Mortensen

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;

D
Dominic Amal Joe F

Simply you can write like this:

<?php
    $data = ["1","2","3","4","5"];
    echo json_encode($data, JSON_NUMERIC_CHECK);
?>

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
Are you sure about this? This won't convert a string to a number, but an array to a JSON string
Yes, @NicoHaase if the number is in string format in an array it will convert into a number.
A
Anuga

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)


No doubt true. But absurdly overkill way to solve something that already has simple solutions provided years earlier. (Just be glad you didn't write it earlier - see very downvoted answer with same approach).
a
aksu

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 Documentation


P
Peter Mortensen

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";
}

u
user1657853

If you don't know in advance if you have a float or an integer, and if the string may contain special characters (like space, €, etc), and if it may contain more than 1 dot or comma, you may use this function:

// 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;
}

Personally, I consider this dubious. Taking an arbitrary, garbage, string, and searching for a number in it, is almost certainly undesireable. Much better to do what php does by default, which is convert (most) garbage strings into "0". Reason: its more obvious what happened, if unexpected strings reach your method - you simply get 0 (unless the string starts with a valid number).
@ToolmakerSteve yes it's problematic, but there is at least this use case where I had no choice: I had to display strings contained in a (not to be modified) sheet "as is", with symbols and so on, and at the same time use the number contained in it.
OK, that makes sense. What will your answer do, if there are multiple numbers scattered throughout the string? Is this approach useful for code that converts a phone number to only the digits? E.g. user enters (123)456-7890, and you want to extract 1234567890 from that? Or is the idea that it finds the first number, so would result in 123 in my example?
It returns the full number
Z
Zahid Gani
//Get Only number from string
$string = "123 Hello Zahid";
$res = preg_replace("/[^0-9]/", "", $string);
echo $res."<br>";
//Result 123

h
hackernewbie

One of the many ways it can be achieved is this:

$fileDownloadCount          =  (int) column_data_from_db;
$fileDownloadCount++;

The second line increments the value by 1.


A
Andy

Now we are in an era where strict/strong typing has a greater sense of importance in PHP, I use json_decode:

$num = json_decode('123');

var_dump($num); // outputs int(123)

$num = json_decode('123.45');

var_dump($num); // outputs float(123.45)

JSON is not PHP
@TV-C-1-5 not sure of the point you are making? Of course JSON is not PHP. PHP provides functions to encode and decode JSON. In the same way PHP provides function to encode and decode base64 - that doesn’t mean base64 is PHP.