I'm trying to extract the numeric value from a string as I need to use it in a calculation for totals.
I read in other threads that I should use the PHP 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 have also tried Regular Expression, but it ends up giving me 1 instead of 1500.
I'm not sure where the mistake is and which method I should use.
If you want just 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); //float(1500)
If you want to use NumberFormatter, which should be better at handling commas instead of periods and other localisation specific differences, you need to make sure that the string is in correct format. The way you're calling the parseCurrency is ok (just make sure you set $curr to ZAR), yet you get false as a result, which means the string format is incorrect.
You can check the format by calling formatCurrency on a number. You will see that the correct format is ZAR1,500.00, not R1,500.00 ZAR.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With