Search code examples
rformattingcurrency

Format negative currency values correctly with minus sign before the dollar sign


I want to format negative currency values correctly with minus sign before the dollar sign.

The following code puts the minus sign after the dollar sign, i.e. $-100

library(scales)
dollar(-100)

How would you change this to desired output i.e. -$100? I don't see an obvious option in documentation https://rdrr.io/cran/scales/man/dollar_format.html


Solution

  • As the output of dollar() is a character vector you can define a new function using chartr on the results to conditionally swap the characters and use ... to pass extra arguments to the original function.

    library(scales)
    
    newdollar <- function(x, ...) ifelse(x < 0, chartr("$-", "-$", dollar(x, ...)), dollar(x, ...))
    newdollar(c(5, -5), suffix = "!!" )
    
    [1] "$5!!"  "-$5!!"