【问题标题】:money representation in RR中的货币表示
【发布时间】:2012-12-11 07:51:22
【问题描述】:

我想知道如何使用 R 处理金钱。这意味着,做算术,打印格式正确的数字等等。

例如我有一些价值观

1.222.333,37 
1.223.444,88

我可以将其转换为数字并对其进行四舍五入,去掉美分,但没有更好的模式可以使用吗?我确实尝试了格式方法,例如:

format(141103177058,digits=3,small.interval=3,decimal.mark='.',small.mark=',')

但没有成功。任何提示或想法?

【问题讨论】:

  • 输出的格式应该一直留到输出,你总是可以编写自己的函数以你想要的方式打印,但是你的问题是什么?
  • “用钱工作”到底是什么意思?
  • 我确实更新了我的问题
  • 另请参阅此问题:stackoverflow.com/q/7147706/269476
  • 感谢@James 的输出,它很棒,但我也想处理保持美分的数字,在向量上运行应用等

标签: r currency


【解决方案1】:

scales 包有一个功能: dollar_format()

install.packages("scales")
library(scales)

muchoBucks <- 15558.5985121
dollar_format()(muchoBucks)

[1] "$15,558.60"

【讨论】:

    【解决方案2】:

    这个呢:

    printCurrency <- function(value, currency.sym="$", digits=2, sep=",", decimal=".") {
      paste(
            currency.sym,
            formatC(value, format = "f", big.mark = sep, digits=digits, decimal.mark=decimal),
            sep=""
      )
    }
    
    printCurrency(123123.334)
    

    【讨论】:

    • 这很好用!谢谢!!
    【解决方案3】:

    假设我们有两个特定的字符值(货币):

    s1 <- "1.222.333,37"
    s2 <- "1.223.444,88"
    

    首先,我们希望 R 显示具有适当位数的数值:

    # controls representation of numeric values
    options(digits=10)
    

    将货币转换为数字可以这样实现:

    # where s is character
    moneyToDouble <- function(s){
      as.double(gsub("[,]", ".", gsub("[.]", "", s)))
    }
    
    x <- moneyToDouble(s1) + moneyToDouble(s2)
    x    
    

    将数字打印为货币:

    # where x is numeric
    printMoney <- function(x){
      format(x, digits=10, nsmall=2, decimal.mark=",", big.mark=".")
    }
    
    printMoney(x)
    

    【讨论】:

    • printMoney(100000) 打印 "1e+05"
    • @user443854 也许 format(scientific = FALSE) 可以解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多