Represent numeric value with typical dollar amount format

后端 未结 4 716
轮回少年
轮回少年 2020-12-03 06:27

I have a data frame storing the dollar amount, it looks like this

> a
  cost
1 1e+05
2 2e+05

I would like it can be shown as this

<
4条回答
  •  执念已碎
    2020-12-03 07:11

    You can use the currency() function from the formattable package. With OP's example

    a <- data.frame(cost = c(1e+05, 2e+05))
    a
    
       cost
    1 1e+05
    2 2e+05
    
    library(formattable)
    a$cost <- currency(a$cost, digits = 0L)
    a
    
          cost
    1 $100,000
    2 $200,000
    

    By default, 2 digits after the decimal point are shown. This has been overruled using the digits parameter to meet OP's expectations.

    The benfit of formattable is that numbers are still numbers even with a format attached, e.g.,

    a$cost2 <- 2 * a$cost
    a
    
          cost    cost2
    1 $100,000 $200,000
    2 $200,000 $400,000
    

提交回复
热议问题