Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 611
Sara Avatar asked Dec 16 '11 04:12

Sara


People also ask

What are the functions that you can use to convert strings to number types in PHP?

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

How do you convert one variable type to another say a string to a number?

Method 1: Using number_format() Function. The number_format() function is used to convert string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure. echo number_format( $num , 2);

How do I convert a string to PHP?

Answer: Use the strval() Function You can simply use type casting or the strval() function to convert an integer to a string in PHP.


3 Answers

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;
like image 133
deceze Avatar answered Oct 11 '22 17:10

deceze


There are a few ways to do so:

  1. Cast the strings to numeric primitive data types:

    $num = (int) "10";
    $num = (double) "10.12"; // same as (float) "10.12";
    
  2. Perform math operations on the strings:

    $num = "10" + 1;
    $num = floor("10.1");
    
  3. Use intval() or floatval():

    $num = intval("10");
    $num = floatval("10.1");
    
  4. Use settype().

like image 241
fardjad Avatar answered Oct 11 '22 15:10

fardjad


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
?>
like image 83
gopeca Avatar answered Oct 11 '22 15:10

gopeca