String to число php

Как преобразовать в число строку в PHP?

Очень часто нам приходится работать с числовой информацией, которая представлена в виде строк. В результате возникает необходимость в преобразования строки в число. Язык программирования PHP предлагает нам несколько возможностей для этого.

Речь идёт о специальных встроенных в PHP функциях, значительно облегчающих программисту задачу преобразования строки в число. Давайте их рассмотрим.

Преобразование строки в число функцией intval()

Представим, что у нас есть строка, включающая в себя один символ — «2». Вот, как будет выглядеть PHP-код преобразования этой строки в число с помощью встроенной функции intval() :

 
$stringNumberToParse = "2"; // var_dump($stringNumberToParse); // string '2' (length=1) // Convert the string to type int $parsedInt = intval($stringNumberToParse); // var_dump(is_int($parsedInt)); // boolean true // var_dump($parsedInt); // int 2 echo $parsedInt;

На выходе получим 2, но уже в виде числа, а не строки.

Давайте пошагово разберём, что же произошло, и расшифруем каждую строчку кода: 1. Объявляется переменная, содержащая строку с символом «1». 2. У нас есть возможность задействовать функцию var_dump() для вывода на экран значения и типа переменной (в ознакомительных целях). 3. Переменная $stringNumberToParse передаётся в функцию intval() в виде аргумента (если речь идёт не о целых числах, используют floatval() ). 4. Функция возвращает нам число, которое мы присваиваем с помощью переменной $parsedInt.

Остаётся добавить, что вышеописанная функция работает в PHP разных версий: 4, 5, 7+.

Преобразование строки в число путём приведения типов

Возможность приведения типов есть во многих языках программирования, и PHP исключением не является. В PHP мы тоже можем поменять тип переменной, применив для этого синтаксис приведения типов: (int)$variable, (float)$variable. Посмотрим, как это выглядит в коде:

 
$stringNumberToParse = "2"; //var_dump($stringNumberToParse); // string '2' (length=1) // Convert the string to type int $parsedInt = (int)$stringNumberToParse; //var_dump(is_int($parsedInt)); // boolean true //var_dump($parsedInt); // int 2 echo $parsedInt;

Результатом будет следующий вывод:

Итак, что тут происходит: 1. Объявляется переменная, содержащая строку 1. 2. Есть возможность задействовать функцию var_dump() для вывода на экран значения и типа переменной (в ознакомительных целях). 3. С помощью синтаксиса приведения типа для переменной устанавливается префикс (int). 4. Полученное числовое значение присваивается переменной $parsedInt.

Приведение типов можно успешно использовать и в PHP 5 и в PHP 7+.

Преобразование строки в число с помощью settype()

Также для выполнения преобразования можно использовать функцию settype() . Посмотрим, как преобразовать 3-символьную строку «555» в число:

Можно заметить, что параметр $str передается в функциею settype() по ссылке, следовательно, операцию присвоения делать не надо.

В принципе, вышеперечисленных способов вполне хватит для выполнения преобразования строки в число в PHP. Если же хотите знать больше, ждём вас на наших курсах!

Источник

intval

Returns the int value of value , using the specified base for the conversion (the default is base 10). intval() should not be used on objects, as doing so will emit an E_WARNING level error and return 1.

Parameters

The scalar value being converted to an integer

The base for the conversion

  • if string includes a "0x" (or "0X") prefix, the base is taken as 16 (hex); otherwise,
  • if string starts with "0", the base is taken as 8 (octal); otherwise,
  • the base is taken as 10 (decimal).

Return Values

The integer value of value on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1.

The maximum value depends on the system. 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval('1000000000000') will return 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807.

Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of integer casting apply.

Changelog

Version Description
8.0.0 The error level when converting from object was changed from E_NOTICE to E_WARNING .

Examples

Example #1 intval() examples

The following examples are based on a 64 bit system.

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
echo intval ( '042' ); // 42
echo intval ( 1e10 ); // 10000000000
echo intval ( '1e10' ); // 10000000000
echo intval ( 0x1A ); // 26
echo intval ( '0x1A' ); // 0
echo intval ( '0x1A' , 0 ); // 26
echo intval ( 42000000 ); // 42000000
echo intval ( 420000000000000000000 ); // -4275113695319687168
echo intval ( '420000000000000000000' ); // 9223372036854775807
echo intval ( 42 , 8 ); // 42
echo intval ( '42' , 8 ); // 34
echo intval (array()); // 0
echo intval (array( 'foo' , 'bar' )); // 1
echo intval ( false ); // 0
echo intval ( true ); // 1
?>

Notes

Note:

The base parameter has no effect unless the value parameter is a string.

See Also

  • boolval() - Get the boolean value of a variable
  • floatval() - Get float value of a variable
  • strval() - Get string value of a variable
  • settype() - Set the type of a variable
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • Type juggling
  • BCMath Arbitrary Precision Mathematics Functions

User Contributed Notes 17 notes

It seems intval is interpreting valid numeric strings differently between PHP 5.6 and 7.0 on one hand, and PHP 7.1 on the other hand.

echo intval ( '1e5' );
?>

will return 1 on PHP 5.6 and PHP 7.0,
but it will return 100000 on PHP 7.1.

$n = "19.99" ;
print intval ( $n * 100 ); // prints 1998
print intval ( strval ( $n * 100 )); // prints 1999
?>

intval converts doubles to integers by truncating the fractional component of the number.

When dealing with some values, this can give odd results. Consider the following:

This will most likely print out 7, instead of the expected value of 8.

For more information, see the section on floating point numbers in the PHP manual (http://www.php.net/manual/language.types.double.php)

Also note that if you try to convert a string to an integer, the result is often 0.

However, if the leftmost character of a string looks like a valid numeric value, then PHP will keep reading the string until a character that is not valid in a number is encountered.

"101 Dalmations" will convert to 101

"$1,000,000" will convert to 0 (the 1st character is not a valid start for a number

"80,000 leagues . " will convert to 80

"1.4e98 microLenats were generated when. " will convert to 1.4e98

Also note that only decimal base numbers are recognized in strings.

"099" will convert to 99, while "0x99" will convert to 0.

One additional note on the behavior of intval. If you specify the base argument, the var argument should be a string - otherwise the base will not be applied.

print intval (77, 8); // Prints 77
print intval ('77', 8); // Prints 63

Источник

How to Convert a String to a Number in PHP

It is possible to convert strings to numbers in PHP with several straightforward methods.

Below, you can find the four handy methods that we recommend you to use.

Applying Type Casting

The first method we recommend you to use is type casting. All you need to do is casting the strings to numeric primitive data types as shown in the example below:

 $num = (int) "10"; $num = (double) "10.12"; // same as (float) "10.12"; ?>

The second method is to implement math operations on the strings. Here is how you can do it:

Using intval() or floatval()

The third way of converting a string to a number is using the intval() or intval() functions. These methods are generally applied for converting a string into matching integer and float values.

 $num = intval("10"); $num = floatval("10.1"); ?>

Using number_format

number_format() is a built-in PHP function that is used to format numbers with grouped thousands and/or decimal points. It takes one or more arguments and returns a string representation of the formatted number.

Here's the basic syntax for the number_format() function:

number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," ) : string

Let's take a closer look at each of the arguments:

  • $number : The number you want to format. This can be a float or an integer.
  • $decimals (optional): The number of decimal points you want to include. The default value is 0.
  • $dec_point (optional): The character to use as the decimal point. The default value is "." (period).
  • $thousands_sep (optional): The character to use as the thousands separator. The default value is "," (comma).

Here's an example of how to use number_format() to format a number with two decimal places and a comma as the thousands separator:

 $number = 1234567.89; $formatted_number = number_format($number, 2, '.', ','); echo $formatted_number; // Output: 1,234,567.89

In this example, the $number variable contains the number we want to format. We use number_format() to format the number with two decimal places, a period as the decimal point, and a comma as the thousands separator. The resulting string is stored in the $formatted_number variable, which we then output to the screen using echo .

number_format() can be very useful when working with monetary values, where it is common to use a specific format for displaying prices or totals. It can also be used to format other types of numeric data, such as percentages or ratios.

When you pass a string to "number_format()", the function first tries to convert the string to a numeric value. If it can't be converted, it will return false. Otherwise, it will format the numeric value as described in my previous answer.

Источник

Читайте также:  Java send http get request
Оцените статью