manish p
manish p

Reputation: 187

Is there a way to put negative sign before dollar sign

Is there a way to put negative sign before dollar sign, For example, below output is positive and the output is fine

paste0("$ ",formatC(2344, format="f", digits=2, big.mark=","))
[1] "$ 2,344.00"

But if the number is negative, dollar sign comes before that.

paste0("$ ",formatC(-2344, format="f", digits=2, big.mark=","))
[1] "$ -2,344.00"

expeted output

> paste0("$ ",formatC(-2344, format="f", digits=2, big.mark=","))
[1] "- $ 2,344.00"

Upvotes: 0

Views: 525

Answers (4)

Eyayaw
Eyayaw

Reputation: 1081

format_dollar <- function(x) {
ifelse(x<0, sprintf("-$%.2f", abs(x)), sprintf("$%.2f", x)) 
}

format_dollar(c(2344, -2344))

# [1] "$2344.00"  "-$2344.00"

Upvotes: 0

s_baldur
s_baldur

Reputation: 33488

Using ifelse()

x <- c(-2344, 2344)
paste0(ifelse(x < 0, "- ", ""), "$ ", formatC(abs(x), format="f", digits=2, big.mark=","))big.mark=","))
# [1] "- $ 2,344.00" "$ 2,344.00" 

Upvotes: 1

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

Using sub:

x <- c(-2344, 2344)
sub("\\$ -", "- $", paste0("$ ",formatC(x, format="f", digits=2, big.mark=",")))
# [1] "- $2,344.00" "$ 2,344.00"

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388962

Probably use scales::dollar ?

scales::dollar(2344)
#[1] "$2,344"

scales::dollar(-2344)
#[1] "-$2,344"

Look at their source code which is written in R by typing scales::dollar in the console. Probably, that is what you were trying to do.

Upvotes: 1

Related Questions