Skip to content

Commit

Permalink
Better behavior for scientific and comma.
Browse files Browse the repository at this point in the history
Fixes #7
  • Loading branch information
hadley committed Feb 23, 2012
1 parent 072d88c commit 571ec73
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
6 changes: 5 additions & 1 deletion NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@
* Simplified algorithm for `discrete_range` that is robust to
`stringsAsFactors` global option. Now, the order of a factor will only be
preserved if the full factor is the first object seen, and all subsequent
inputs are subsets of the levels of the original factor.
inputs are subsets of the levels of the original factor.

* `scientific` ensures output is always in scientific format and off the
specified number of significant digits. `comma` ensures output is never in
scientific format. (Fixes #7)
5 changes: 3 additions & 2 deletions R/formatter.r
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ comma_format <- function(...) {
#' @export
#' @rdname comma_format
comma <- function(x, ...) {
str_trim(formatC(x, ..., big.mark = ","))
format(x, ..., big.mark = ",", scientific = FALSE, trim = TRUE)
}

#' Currency formatter: round to nearest cent and display dollar sign.
Expand Down Expand Up @@ -80,7 +80,8 @@ scientific_format <- function(digits = 3, ...) {
#' @export
#' @rdname scientific_format
scientific <- function(x, digits = 3, ...) {
format(x, trim = TRUE, digits = digits, ...)
x <- signif(x, digits)
format(x, trim = TRUE, scientific = TRUE, ...)
}

#' Parse a text label to produce expressions for plotmath.
Expand Down
29 changes: 29 additions & 0 deletions inst/tests/test-formatter.r
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
context("Formatters")

test_that("comma format always adds commas", {
expect_equal(comma(1e3), "1,000")
expect_equal(comma(1e6), "1,000,000")
expect_equal(comma(1e9), "1,000,000,000")
})

test_that("scientific format shows specific sig figs", {
expect_equal(scientific(123456, digits = 1), "1e+05")
expect_equal(scientific(123456, digits = 2), "1.2e+05")
expect_equal(scientific(123456, digits = 3), "1.23e+05")

expect_equal(scientific(0.123456, digits = 1), "1e-01")
expect_equal(scientific(0.123456, digits = 2), "1.2e-01")
expect_equal(scientific(0.123456, digits = 3), "1.23e-01")
})


test_that("formatters don't add extra spaces", {
has_space <- function(x) any(grepl("\\s", x))
x <- 10 ^ c(-1, 0, 1, 3, 6, 9)

expect_false(has_space(comma(x)))
expect_false(has_space(dollar(x)))
expect_false(has_space(percent(x)))
expect_false(has_space(percent(x)))
expect_false(has_space(scientific(x)))
})

0 comments on commit 571ec73

Please sign in to comment.