0

I have a number like that : 342.50 EUR. How to table only the number : 342.50 I tried this, but it's not the result that I want

$str = '342.50 EUR';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);

result : Array ( [0] => Array ( [0] => 342 [1] => 00 ) )

0

4 Answers 4

2

If you are fine with losing the last 0 then you can simply use floatval:

$str = '342.50 EUR';

echo floatval($str); // 342.5
Sign up to request clarification or add additional context in comments.

Comments

1

It's as simple as this ...

$str = +'342.50 EUR';

or

$str = '342.50 EUR';
$str = +$str;

This way, no need to know about the type of number (int or float).

This is a compact version of 0 + '342.50 EUR'. PHP will cast the string to the first number part it can find in it. If no number is there, then it will result to zero.

Comments

0

You could cast it to a float :

$str = '342.50 EUR';    
$float = floatval($str);    

And after, you can chose the number of decimals to show with number_format :

echo(number_format($float, 2));

Comments

-2

You can do this in two steps:

  1. Remove the currency name from the string.
  2. Then convert the remaining string into a float value.

These steps can be performed in these lines:

$string = '342.50 EUR';
$string = str_replace(" EUR", "", $string);
$float_value_of_string = floatval($string);
echo $float_value_of_string; //342.50

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.