4

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,

1
  • Please edit your question to clarify whether you mean floats or integers. Otherwise I'll do it and assume you mean floats. Commented Feb 19, 2011 at 17:15

4 Answers 4

9

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Great trick! And great help. Thanks for your knowledge. Best Regards.
Hi, I have been doing come UnitTest's. If I input "m 1.70" will not return "1.70". Any clues how how to solve? Best Regards,
@André: You may want to ask a new question.
3

you can get it by

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

Update :

echo (float) $string;

2 Comments

No need for the trouble, a direct cast will strip the space and the units away.
Yaa..! I got that after your answer.
2

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

Comments

-1
$integer = intval($string);

Enjoy :D

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.