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.

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.