How to convert a string into number in PHP?

Today, We want to share with you convert string to number in php.In this post we will show you php string to double, hear for php intval vs int we will give you demo and example for implement.In this post, we will learn about php Two Decimal Places without rounding off with an example.

php get number from string

Using type casting, Using intval() and floatval() Function or By adding 0 or by performing mathematical operations.

Read Also:  php parse XML File SimpleXML

Use Type Casting

Example 1: Using gettype() Function.

<?php
$num = "2.75";
 
// Cast to integer
$int = (int)$num;
echo gettype($int) . "<br>"; // Results: integer
echo $int . "<br>"; // Results: 2
 
// Cast to float
$float = (float)$num;
echo gettype($float) . "<br>"; // Results: double
echo $float; // Results: 2.75
?>

Example 2:

<?php
echo intval(2) . "<br>";       // Results: 2
echo intval(2.75) . "<br>";    // Results: 2
echo intval('34') . "<br>";    // Results: 34
echo intval('+34') . "<br>";   // Results: 34
echo intval('-34') . "<br>";   // Results: -34
echo intval(034) . "<br>";     // Results: 28
echo intval('034') . "<br>";   // Results: 34
echo intval(1e10) . "<br>";    // Results: 10000000000
echo intval('1e10') . "<br>";  // Results: 1 (return 100000 in PHP 7.1+)
echo intval(0xff) . "<br>";    // Results: 255
echo intval('0xff') . "<br>";  // Results: 0
?>

Example 3: PHP Numbers
here simple Example to convert these types of values, ‘3’, ‘2.34’, ‘0.234343’,

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

I hope you get an idea about php convert string to float with 2 decimal.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Read Also:  check array empty php

Related FAQ

Here are some more FAQ related to this Article:

  1. Read Also:  codeigniter print last query - PHP Examples
  2. Read Also:  Laravel Number of days between two inputted dates
  3. Read Also:  PHP Resize Image Upload Example
  4. Read Also:  Laravel 5.6 Sending Emails using SMTP Tutorial
  5. Read Also:  PHP string to int | php cast to int
  6. Read Also:  Error incorrect format parameter phpmyadmin
  7. Read Also:  Create a Registration and Login System with PHP and MySQL
  8. Read Also:  Woocommerce Product publish, update and delete hooks
  9. Read Also:  PHP Laravel delete files from Public Folder
  10. Read Also:  How to convert string number into month name in PHP
CLOSEX