Mark Neal
Mark Neal

Reputation: 1206

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

Upvotes: 5

Views: 2768

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388962

One hacky way is to add a "-" sign explicitly to the absolute value of amount if amount is less than 0.

library(scales)
amount <- c(100, -200, -50)
ifelse(amount < 0, paste0("-", dollar(abs(amount))), dollar(amount))
#[1] "$100"  "-$200" "-$50" 

Upvotes: 1

lroha
lroha

Reputation: 34416

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!!"

Upvotes: 4

Related Questions