Getting numeric value from currency string in PHP

I am trying to extract a numeric value from a string as I need to use it to calculate totals.

I read in other threads that I should be using PHP's NumberFormatter function .

Here's my code ...

PHP

$fmt = new NumberFormatter( 'za_ZA', NumberFormatter::CURRENCY );
$num = "R1,500.00 ZAR";
var_dump($fmt->parseCurrency($num, $curr));

      

... and the corresponding output I get.

Html

<pre class="xdebug-var-dump" dir="ltr"><small>boolean</small> <font color="#75507b">false</font>
</pre>

      

I also tried Regular Expression but ended up being given 1 instead of 1500.

I'm not sure where the error is and what method I should be using.

+3


source to share


1 answer


If you only want the number and don't care about the currency itself, this will work for you:

$num = "R1,500.00 ZAR";
$value = floatval(preg_replace('/[^\d\.]+/', '', $num);
var_dump($value);

      

If you want to use NumberFormatter , which should be better at handling commas instead of periods and other localization differences, you need to make sure the string is in the correct format. The way you call parseCurrency is ok (just make sure you set $ curr to ZAR ), but you get false which means the string is not formatted correctly.



You can check the format by calling formatCurrency on the number. You will see that the correct format is ZAR1,500.00 and not R1,500.00 ZAR .

A small example:

<?
  $fmt = new NumberFormatter( 'za_ZA', NumberFormatter::CURRENCY );
  $curr = 'ZAR';
  $string = $fmt->formatCurrency(1500,$curr);
  var_dump($string); //displays "ZAR1,500.00
  $value = $fmt->parseCurrency($num, $curr);
  var_dump($value); //displays 1500

      

+2


source







All Articles