Php str to number one

PHP: Convert String to Number

While programming in PHP, there might be a situation where you have to convert a string into an integer. But we know that PHP does not need or support explicit type definition while declaring a variable. So you have to force a string to be converted into an integer.

We will look at the various ways by which a string can be converted into an integer in PHP in this article.

Why Do We Need to Convert String to Integer in PHP?

Sometimes you may need to convert a string into an integer, float or any other data type. This is because the data or values you are working on might be of a different data type. You might have an integer in a string format from the user. So you have to convert this string into a number for performing operations in the program.

Using number_format() Function

The number_format() function is an in-built method in PHP that is used for converting a string with grouped thousands. It takes 4 parameters:

string number_format ( $number, $decimals, $decimalpoint, $sep )

  • $number — This is the number to be formatted. If you don’t set any other parameters, this number will be formatted without any decimals
  • $decimals — This is the optional parameter that is used for specifying the decimals
  • $decimalpoint — This specifies the string used for mentioning the decimal point
  • $sep — This is a string specifying the thousands separator

If the method successfully converts the string, it returns the formatted number. On failure, it returns an E_WARNING error message.

number_format($string); // string into integer number_format($string,2); // string into float

Code Example:

Float Value: '.number_format($string,2); >else < echo 'Not a numaric value'; >?>
Integer Value: 25 Float Value: 25.00

Explanation:
In this program, an integer in the form of a string is assigned to a variable called $string. Then the is_numeric() checks the value of the variable and then formats it using the number_format() method. if the value is not numeric, the echo statement prints out the string “Not a numeric value”.

Using Type Casting settype()

The settype() method is used for setting the type of a variable and modify its existing type.

  • $variable – This is the variable that needs to be converted
  • $type – This is the type you want to convert the variable to
(int)$string; // string into integer (float)$string; // string into float (double)$string; // string into double

Code Example:

// Declare string value $string = '25'; $stringf = '25.99'; $stringd = '25.99'; // Check if string in numaric if (is_numeric($string))< // Convert string to integer using int type cast echo 'Integer Value: '.(int)$string; >else < echo 'Not a numaric value'; >// Check if string in numaric if (is_numeric($stringf))< // Convert string to float using float type cast echo '
Float Value: '.(float)$stringf; >else < echo 'Not a numaric value'; >// Check if string in numaric if (is_numeric($stringf))< // Convert string to float using float type cast echo '
Double Value: '.(double)$stringd; >else
Integer Value: 25 Float Value: 25.99 Double Value: 25.99

Explanation:
In this code, you can observe that typecasting is used for converting the string into an integer. After evaluating whether the given variable has a string value or not using the is_numeric method, the line echo ‘Integer Value: ‘.(int)$string; converts the string into an integer. Similarly, later on in the program, variables are converted to double and float, by mentioning the data type along with the variable name.

Читайте также:  Си шарп коды символов

Using intval() and floatval() Function

The intval() function is used for returning the integer value of a variable.

It takes two parameters:

  • $var – This is the variable that you want to convert into an integer
  • $base – This optional parameter specifies the base for conversion. If $var has 0x as a prefix, 16 is taken as the base. If $var starts with 0, 8 is taken as the base

The floatval() method is used for obtaining the float value of a variable. It takes only one parameter $var, that is the value whose float value needs to be determined.

intval($string); // Convert string to integer floatval($string); // Convert string to float

Code Example:

// Declare string value $string = '25.99'; // Check if string in numaric if (is_numeric($string))< // Convert string to integer using intval function echo 'Integer Value: '.intval($string); // Convert string to float using floatval function echo '
Integer Value: '.floatval($string); >else
Integer Value: 25 Integer Value: 25.99

Explanation:
You can see that in the example, the intval() converts the value stored in the $string variable into an integer. Later the same value is converted into a float using the floatval() method.

Performing Mathematical Operations on String Value

Here, no in-built functions are used for a string to be converted to an integer.

By Adding Number «0» to String

Code Example:

Float Value: ' . ($string + 0.00); >else < echo 'Not a numaric value'; >?>
Integer Value: 25.23 Float Value: 25.23

Explanation:
This is one of the easiest ways to convert a string into an integer. In this program, 0 is added to the string, which converts it into a number. By adding the string with 0.00 the value is converted into a float. This conversion is done by PHP automatically.

By Multiply Number «1» to String

Code Example:

Float Value: ' . ($string * 1.00); >else < echo 'Not a numaric value'; >?>
Integer Value: 25.23 Float Value: 25.23

Explanation:
Another simple method for a string to be converted to an integer is by multiplying it by 1. So, the string 25.23 is multiplied by 1 to get an integer value.

Conclusion:

All these methods are applied when you get a number as a string but want to perform some mathematical operations on it. Although the intval(), float(), number_format() and type casting methods are very effective, adding 0 and multiplying 1 to a string is a very fast way to convert it into a number.

  • Learn PHP Language
  • PHP Interview Questions and Answers
  • PHP Training Tutorials for Beginners
  • Display Pdf/Word Document in Browser Using PHP
  • Call PHP Function from JavaScript
  • Call a JavaScript Function from PHP
  • PHP Pagination
  • Alert Box in PHP
  • Php Count Function
  • PHP Filter_var ()
  • PHP array_push Function
  • strpos in PHP
  • PHP in_array Function
  • PHP strtotime() function
  • PHP array_merge() Function
  • explode() in PHP
  • implode() in PHP
  • PHP array_map()

Источник

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.

Читайте также:  Php get filename and extension

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.

Читайте также:  Python requests http error codes

«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.

Источник

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