dtn51137 2017-06-26 12:18
浏览 149
已采纳

获取基于符号的货币代码

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.

  • 写回答

1条回答 默认 最新

  • duan1227 2017-06-26 12:28
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么