0

I've made this function which will convert any 9 or less to a word and will also format large numbers by inserting a comma:

library(english); library(stringr)

reportNumber <- function (number) {
  ifelse(number > 9, str_trim(format(number, big.mark= ",", scientific = F)), as.character(english(number)))
}

The function works like this:

reportNumber(c(0, 9, 10, 100, 1000, 10000))

# [1] "zero"   "nine"   "10"     "100"    "1,000"  "10,000"

But if the number has a decimal point, the function errors:

reportNumber(c(0.1, 9.1, 10.1, 100.1, 1000.1, 10000.1))

I need to make the function test whether a number has a decimal point, and if true, then just print the number unformatted. So the output should simply be:

c(0.1, 9.1, 10.1, 100.1, 1000.1, 10000.1)

# [1]     0.1     9.1    10.1   100.1  1000.1 10000.1
luciano
  • 13,158
  • 36
  • 90
  • 130
  • `grepl(".", number), ...)` may work for that problem. Or possibly `is.double` – Rich Scriven Apr 23 '14 at 18:32
  • Richard's basic idea is fine, but `.` is a special character in regex. You probably would need to specify `fixed = TRUE` in `grepl`. – joran Apr 23 '14 at 18:40
  • Thanks @joran. You'd also want to remove the `, ...)` since I forgot to cut that out when I edited the comment. – Rich Scriven Apr 23 '14 at 18:43

1 Answers1

1

Your question essentially boils down to checking if a number is an integer, which has been addressed before on SO. You might try:

reportNumber <- function (number) {
  ifelse(number %% 1 != 0, as.character(number),
         ifelse(number > 9,
                str_trim(format(number, big.mark= ",", scientific = F)),
                as.character(english(number))))
}
reportNumber(c(0, 9, 10, 100, 1000, 10000))
# [1] "zero"   "nine"   "10"     "100"    "1,000"  "10,000"
reportNumber(c(0.1, 9.1, 10.1, 100.1, 1000.1, 10000.1))
# [1] "0.1"     "9.1"     "10.1"    "100.1"   "1000.1"  "10000.1"
Community
  • 1
  • 1
josliber
  • 43,891
  • 12
  • 98
  • 133