2

I am currently working with an API where instead of floats or integers for currency I receive strings like these.

  • $2.49
  • £2.49
  • €2.49
  • etc.

The issue with that is that I need to store the value and currency separately but the currency needs to be stored as ISO Code, so for example EUR, USD or GBP instead of € and $.

Is there any way in PHP to get the currency code based on a currency symbol using the NumberFormatter or something like that?

Currently I just have a very long list of currency symbols and names which I use to do things like string_contains('$2.49', '$') to check for a certain currency.

Chris Mayer
  • 187
  • 3
  • 10
  • 6
    There are be no general solution because multiple currencies use the same symbol. Eg. AUD, NZD, USD, … all use the dollar symbol. – Richard Jun 26 '17 at 12:20
  • @GauravDave — That does the opposite of what the question is asking for. – Quentin Jun 26 '17 at 12:23

1 Answers1

6

You could work with NumberFormatter::parseCurrency:

<?php
$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);

echo "#1: ".$fmt->parseCurrency("$2.49", $curr)." in $curr<br>";
echo "#2: ".$fmt->parseCurrency("£2.49", $curr)." in $curr<br>";
echo "#3: ".$fmt->parseCurrency("€2.49", $curr)." in $curr<br>";
?>

Prints:

#1: 2.49 in USD
#2: 2.49 in GBP
#3: 2.49 in EUR

Note that Richard's comment about multiple currencies using the same symbol still applies but might be handled by specifying different locales for the NumberFormatter:

<?php
$fmt = new NumberFormatter('en_AU', NumberFormatter::CURRENCY);

echo "#1: ".$fmt->parseCurrency("$2.49", $curr)." in $curr<br>";
?>

Would e.g. change the first output to:

#1: 2.49 in AUD
Marvin
  • 13,325
  • 3
  • 51
  • 57