【问题标题】:Is there an R library or function for formatting international currency strings?是否有用于格式化国际货币字符串的 R 库或函数?
【发布时间】:2020-07-12 02:21:14
【问题描述】:

这是我正在使用的 JSON 数据的 sn-p:

{
   "item" = "Mexican Thing",
   ...
   "raised": "19",
   "currency": "MXN"
},
{
   "item" = "Canadian Thing",
   ...
   "raised": "42",
   "currency": "CDN"
},
{
   "item" = "American Thing",
   ...
   "raised": "1",
   "currency": "USD"
}

你明白了。

我希望有一个函数可以接收标准货币缩写和数字并输出适当的字符串。理论上我可以自己写这个,除非我不能假装我知道这些东西的所有来龙去脉,而且我一定会花费数天和数周的时间对我没有想到的错误或边缘情况感到惊讶。我希望已经编写了一个库(或至少是一个 web api)可以处理这个问题,但我的谷歌搜索到目前为止没有任何用处。

这是我想要的结果示例(假设“货币”是我正在寻找的函数)

currency("USD", "32") --> "$32"
currency("GBP", "45") --> "£45"
currency("EUR", "19") --> "€19"
currency("MXN", "40") --> "MX$40"

【问题讨论】:

    标签: r string-formatting currency


    【解决方案1】:

    假设你的真实 json 是有效的,那么它应该是比较简单的。我将提供一个有效的 json 字符串,在这里修复三个无效部分:= 应该是 :... 显然是占位符;它应该是一个包含在[] 中的列表:

    js <- '[{
       "item": "Mexican Thing",
       "raised": "19",
       "currency": "MXN"
    },
    {
       "item": "Canadian Thing",
       "raised": "42",
       "currency": "CDN"
    },
    {
       "item": "American Thing",
       "raised": "1",
       "currency": "USD"
    }]'
    with(jsonlite::parse_json(js, simplifyVector = TRUE), 
         paste(raised, currency))
    # [1] "19 MXN" "42 CDN" "1 USD" 
    

    编辑:为了更改特定的货币字符,不要太难:只需实例化一个 lookup 向量,其中"USD"(例如)前置"$" 并将""(无)附加到raised 字符串。 (我说两者都是前置/附加,因为我相信某些货币总是后数字......我可能是错的。)

    pre_currency <- Vectorize(function(curr) switch(curr, USD="$", GDP="£", EUR="€", CDN="$", "?"))
    post_currency <- Vectorize(function(curr) switch(curr, USD="", GDP="", EUR="", CDN="", "?"))
    with(jsonlite::parse_json(js, simplifyVector = TRUE), 
         paste0(pre_currency(currency), raised, post_currency(currency)))
    # [1] "?19?" "$42"  "$1"  
    

    有意在此处将"MXN" 排除在向量之外,以证明您需要一个默认设置,"?"(前/后)。您可以选择不同的默认/未知货币值。

    另一种选择:

    currency <- function(val, currency) {
      pre <- sapply(currency, switch, USD="$", GDP="£", EUR="€", CDN="$", "?")
      post <- sapply(currency, switch, USD="", GDP="", EUR="", CDN="", "?")
      paste0(pre, val, post)
    }
    with(jsonlite::parse_json(js, simplifyVector = TRUE), 
         currency(raised, currency))
    # [1] "?19?" "$42"  "$1"  
    

    【讨论】:

    • 我已经用我希望的输出示例更新了我的问题。基本上,我正在寻找对货币有用的东西,就像 lubridate 对日期的作用一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    相关资源
    最近更新 更多