Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 640
Mark Neal Avatar asked Apr 11 '19 00:04

Mark Neal


People also ask

Do you put minus before dollar sign?

The negative sign before the number but behind the currency symbol. The negative sign after the number. Enclosed in parentheses. Most currencies use the same decimal and thousands separator that other numbers in the locale use, but this is not always true.

How do you write a negative number with a dollar sign?

For negative numbers, you can display the number with a leading red minus sign surrounded by parentheses or in red surrounded by parentheses. Currency formats—The currency formats are similar to the number formats, except that the thousands separator is always used.

What is the correct way to write a negative dollar amount?

The standard accounting way is always to show negative numbers in parentheses. If you want to appeal to primarily financial professionals, that's the accepted practice.

How do you show a negative amount?

You can display negative numbers by using the minus sign, parentheses, or by applying a red color (with or without parentheses).


1 Answers

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!!"
like image 174
Ritchie Sacramento Avatar answered Sep 20 '22 02:09

Ritchie Sacramento