简体   繁体   中英

How to convert a string number with text into numeric number

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 ) )

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

$str = '342.50 EUR';

echo floatval($str); // 342.5

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.

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));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM