Php stroka в число

Преобразование строки в число в PHP

В этой статье показано, как преобразовать числовую строку в число в PHP 8.

1. Использование кастинга

Вы можете преобразовать строку в числовой тип, явно приведя строку. Например, следующее приводит строку к целому числу:

Вы также можете преобразовать числовую строку в другие примитивные типы данных. Например, следующее приводит строку к типу с плавающей запятой:

2. Использование + оператор

Лучший вариант — просто добавить ноль к строке, что автоматически преобразует строку в int или float в зависимости от ситуации. Это избавляет от необходимости проверять, является ли строка типом int или float перед приведением.

В качестве альтернативы вы можете использовать тождественный арифметический оператор для преобразования числовой строки в int или float. Выражение +$s преобразует строку $s к соответствующему int или float, как показано ниже:

3. Использование intval() а также floatval() функция

PHP предоставляет встроенную функцию intval() чтобы получить целочисленное значение указанной переменной. Вы можете преобразовать строку в int, используя эту функцию, следующим образом:

Читайте также:  Unexpected error while obtaining ui hierarchy java lang reflect invocationtargetexception

Чтобы получить значение с плавающей запятой указанной переменной, вы можете использовать встроенную функцию floatval() . Следующий код использует его для преобразования строки в число с плавающей запятой:

Следует отметить, что оба intval() а также floatval() может выполняться медленнее, чем рассмотренные ранее арифметические операторы приведения и сложения/идентификации.

Это все, что нужно для преобразования числовой строки в число в PHP 8.

Средний рейтинг 5 /5. Подсчет голосов: 1

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

Преобразовать строку в число (PHP)

В PHP преобразовать строку в число в PHP можно тремя способами. Функцией bool settype (mixed &var, string type) , функцией int intval(mixed var [,int base]) или приведением к типу — (int) или (integer) .

Пример

Например есть строка «123» нужно преобразовать ее в тип integer .

Приведение к типу (int)

settype()

intval()

Быстродействие

В плане быстродействия самым быстрым оказался первый способ (приведение к типу — (int)$str ), номером 2 оказался способ settype() и самым медленным оказался способ intval() .

Скорость измерялась обычным способом, строка «123» 1 миллион раз преобразовывалась в тип int .

Категории

Читайте также

  • Строку в верхний регистр (PHP)
  • Строку в нижний регистр (PHP)
  • Как инвертировать строку (PHP)
  • Как обрезать строку (PHP)
  • Как обрезать строку (JavaScript)
  • Первые N символов строки цифры (PHP)
  • str_repeat (JavaScript)
  • Разделить строку по разделителю (PHP)
  • Первую букву в верхний регистр (JavaScript)
  • Повторение строки (PHP)
  • Определить поискового бота (PHP)
  • str_pad (JavaScript)

Комментарии

Привет от кво мастера Америке

Вход на сайт

Введите данные указанные при регистрации:

Социальные сети

Вы можете быстро войти через социальные сети:

Источник

Манипуляции с типами

PHP не требует (и не поддерживает) явного типа при определении переменной; тип переменной определяется по контексту, в котором она используется. То есть, если вы присвоите значение типа string переменной $var , то $var станет строкой. Если вы затем присвоите $var целочисленное значение, она станет целым числом.

Примером автоматического преобразования типа является оператор сложения ‘+’. Если какой-либо из операндов является float , то все операнды интерпретируются как float , и результатом также будет float . В противном случае операнды будут интерпретироваться как целые числа и результат также будет целочисленным. Обратите внимание, что это НЕ меняет типы самих операндов; меняется только то, как они вычисляются и сам тип выражения.

$foo = «0» ; // $foo это строка (ASCII 48)
$foo += 2 ; // $foo теперь целое число (2)
$foo = $foo + 1.3 ; // $foo теперь число с плавающей точкой (3.3)
$foo = 5 + «10 Little Piggies» ; // $foo это целое число (15)
$foo = 5 + «10 Small Pigs» ; // $foo это целое число (15)
?>

Если последние два примера вам непонятны, смотрите Преобразование строк в числа.

Если вы хотите, чтобы переменная принудительно вычислялась как определенный тип, смотрите раздел приведение типов. Если вы хотите изменить тип переменной, смотрите settype() .

Если вы хотите протестировать любой из примеров, приведенных в данном разделе, вы можете использовать функцию var_dump() .

Замечание:

Поведение автоматического преобразования в массив в настоящий момент не определено.

К тому же, так как PHP поддерживает индексирование в строках аналогично смещениям элементов массивов, следующий пример будет верен для всех версий PHP:

Приведение типов

Приведение типов в PHP работает так же, как и в C: имя требуемого типа записывается в круглых скобках перед приводимой переменной.

Допускаются следующие приведения типов:

  • (int), (integer) — приведение к integer
  • (bool), (boolean) — приведение к boolean
  • (float), (double), (real) — приведение к float
  • (string) — приведение к string
  • (array) — приведение к array
  • (object) — приведение к object
  • (unset) — приведение к NULL (PHP 5)

Приведение типа (binary) и поддержка префикса b были добавлены в PHP 5.2.1

Обратите внимание, что внутри скобок допускаются пробелы и символы табуляции, поэтому следующие примеры равносильны по своему действию:

Приведение строковых литералов и переменных к бинарным строкам:

Замечание:

Вместо использования приведения переменной к string , можно также заключить ее в двойные кавычки.

$foo = 10 ; // $foo — это целое число
$str = » $foo » ; // $str — это строка
$fst = (string) $foo ; // $fst — это тоже строка

// Это напечатает «они одинаковы»
if ( $fst === $str ) echo «они одинаковы» ;
>
?>

Может быть не совсем ясно, что именно происходит при приведении между типами. Для дополнительной информации смотрите разделы:

Источник

How to Convert a String to a Number in PHP

PHP is a weakly typed language. This means that when initializing a variable in PHP, one doesn’t need to declare the variable type. PHP implicitly declares a data type for your variable. This can save you from prospective type errors in your code.

When working with programming languages, it is quite common to want to do things with numbers that are represented as strings. For example, performing arithmetic operations, responding to a client request, feeding the data to a database etc. Even though PHP helps with implicit type conversion in some cases, it is important to know about appropriate methods that can facilitate type conversion.

In this guide, we’ll explore the different ways to convert a string to a number in PHP.

Use the links below to skip ahead in the tutorial:

Background: Types of PHP Numbers

Numbers in PHP can take four forms:

Here, integers and floats represent the more commonly used number formats in programming languages, and in everyday life. On the other hand, Infinity and NaN are not as well-defined and are more likely to be encountered in edge-cases. Let us look at these in some more depth.

Integers

Integers are the numbers that do not contain a decimal component. They constitute the set Z=<. -3,-2,-1,0,1,2,3..>. If you initialise a variable in PHP as a number that does not have a decimal component, it takes the integer data type (unless it has a value greater than PHP_INT_MAX).

You can verify if a variable is an integer by using the is_int() function, as shown below.

Float numbers are those that contain a decimal component or are represented in an exponential form. These numbers encompass a higher range of numbers, take up more bytes per number, and are precise up to 14 decimal places. Here are some examples of float numbers —

0.08, 2.39, 132.5, 2.0, 1.3e5, 2e10, etc.

It is important to note that arithmetic operations performed between a float number and an integer always return a float number (even if the returned number does not need a decimal part). For example —

You can verify if a variable is a float number by using the is_float() function, as shown below.

‘INF’ in PHP stands for infinity. In programming languages, it is commonly used to represent any number that is greater than the maximum possible float value (which is platform-dependent in PHP).

INF is usually encountered any time you happen to divide an integer or float number by zero.

INF can also be in the negative form, which can be encountered when you perform an operation like log(0) .

You can verify if a variable is INF by using the is_infinite() or is_finite() function as shown below.

PHP NaN

NaN stands for ‘Not a Number’. It represents outputs of mathematical operations that can not be defined. For example, the arc cosine of x, i.e. acos(x) is undefined for x > 1 and x < 1.

You can verify if a variable is NaN by using the is_nan() function as shown below.

Convert a String to a Number Using Type Casting

To convert a PHP string to a number, we can perform type casting using (int) or (float) keywords as shown below.

Similarly, we can also cast PHP strings to float values using (float) .

Using (int) , we can also convert PHP strings that represent float numbers (eg. “1.78”, “18.19”) directly to integers. This operation floors the float number (eg. “18.19”) down to it’s nearest integer (18). For example —

Convert a String to a Number Using intval()

To convert a PHP string to a number, we can also use the intval() or floatval() function. Below are a few examples of intval() ’s usage.

intval() can also be used to convert strings from hexadecimal (base 16) and octal (base 8) number systems to integers of decimal representations (base 10). The intval() function can also use a second parameter that specifies the base for conversion. The default base value is 10 (for decimal representations).

Apart from string to integer conversion, intval() can also be used to convert strings of float numbers to integers.

Similarly, we can use floatval() to convert to float numbers.

Convert a String to a Number Implicitly using Mathematical Operations

If you have a number that is initialized as a string in your code, PHP allows you to perform arithmetic operations directly on that string variable. This means that PHP implicitly performs the type conversion so that your code doesn’t raise an error. These are seemingly some of the advantages of weakly (or loosely) typed languages like PHP.

Let’s see how we can leverage this implicit type conversion to our advantage.

As can be seen above, even though we started with a string variable, a trivial arithmetic operation has implicitly converted it to an integer.

Agreed, this is not the most elegant approach to convert a string to a number, but in many cases, it can still save you from an explicit type conversion.

Formatting Number Strings Using number_format()

Before we close, I’d like to shed some light on how we can format number strings (numbers stored as strings) to improve presentation.

Some posts on the internet incorrectly claim that number_format() function can be used to convert a string to a number. This is not true.

The number_format() function can be used to format numbers that are stored in the form of strings — by adding commas to separate between thousands and/or specifying the number of decimal places. The function always returns a formatted string (not a number variable) and can be used as shown below —

number_format(string_number, n_decimal_places , decimal_point_symbol, separator_symbol)

All arguments here, except the first one ( string_number ) are optional.

Let’s look at a few examples.

Test it for Yourself

In this post, we looked at different types of numbers in PHP — integers, float numbers, INF (infinity), and NaN. We also looked at how we can convert PHP strings into numbers using various methods — by typecasting, using intval() and floatval() methods, and also by implicit conversion using mathematical operations. We also looked at how we can use the number_format() function to format number strings to improve presentation.

Now that you know about numbers in PHP, about how to convert strings to numbers and about number string formatting, go ahead and try it out. Choose whichever conversion method suits you best and implement what you learned in this post.

Stay healthy, stay safe! Happy coding!

Follow Us on Social Media!

Источник

Оцените статью