Reputation: 187
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
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
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
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
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