Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Transform String to Float

I need to transform a String to a Float.

I will receive Strings like this:

$string  = "1.70 m";
$string2 = "2.445 m";

How can I easly transform this strings to:

$float1 = 1.70;
$float2 = 2.445;

Can someone give me some clues?

Best Regards,

like image 278
André Avatar asked Dec 13 '22 15:12

André


2 Answers

Those are floats, not integers. Integers do not have decimal points.

To answer your question, you can simply typecast the strings directly, the conversion will strip off the units as those aren't numeric characters:

$string = "1.70 m";
$float = (float) $string;
like image 86
BoltClock Avatar answered Dec 15 '22 06:12

BoltClock


you can get it by

echo (float)array_shift(implode(' ', $string));

Update :

echo (float) $string;
like image 31
Gaurav Avatar answered Dec 15 '22 05:12

Gaurav