André
André

Reputation: 25584

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,

Upvotes: 4

Views: 6730

Answers (4)

Gaurav
Gaurav

Reputation: 28775

you can get it by

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

Update :

echo (float) $string;

Upvotes: 3

BoltClock
BoltClock

Reputation: 724592

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;

Upvotes: 9

Gavin Anderegg
Gavin Anderegg

Reputation: 6391

The easiest way to do this is probably with the floatval() function:

http://ca.php.net/manual/en/function.floatval.php

For exmaple:

floatval("1.70 m");

gives you:

1.7

Upvotes: 2

ThorDozer
ThorDozer

Reputation: 104

$integer = intval($string);

Enjoy :D

Upvotes: -1

Related Questions