good-code ex 5: simplifying function interfaces, formatC

The formatC function is very flexible, but has a complicated interface. Take a look at it using sig(formatC).

Write a function that calls formatC to print currency values in US dollars. (Values should be prefixed with a $ symbol, be in fixed rather than scientific format, and have two decimal places. For example, $999.99.) Hints: The digits argument specifies the number of decimal places, and format = "f" denotes fixed format.

All you need is paste0 and formatC.

format_as_usd <- function(x)
{
  paste0("$", formatC(x, digits = 2, format = "f"))
}

Usage is as

format_as_usd(999999.999)
## [1] "$1000000.00"