Skip to content

Instantly share code, notes, and snippets.

@mcanouil
Last active February 2, 2024 23:34
Show Gist options
  • Save mcanouil/90bf1bc2e57d39b6b9d0691900639473 to your computer and use it in GitHub Desktop.
Save mcanouil/90bf1bc2e57d39b6b9d0691900639473 to your computer and use it in GitHub Desktop.
Format Number
# # MIT License
#
# Copyright (c) 2024 Mickaël Canouil
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
format_number <- function(x, prefix = NULL) {
x_sign <- signif(x, digits = 3)
x_fmt <- character(length = length(x))
x_fmt[x == 0] <- 0
x_fmt[abs(x) > 1e-2 & x != 0] <- prettyNum(
x = x_sign[abs(x) > 1e-2 & x != 0],
scientific = FALSE,
justify = "none",
digits = 3,
nsmall = 3,
trim = TRUE,
width = 3
)
x_fmt[abs(x) <= 1e-2 & x != 0] <- gsub(
"^(.*)e[+]*([-]*)0*(.*)$",
"\\1 %*% 10^\\2\\3",
prettyNum(
x = x_sign[abs(x) <= 1e-2 & x != 0],
scientific = TRUE,
justify = "none",
digits = 3,
nsmall = 3,
trim = TRUE,
width = 3
)
)
if (is.null(prefix)) {
gsub("^1 \\%\\*\\% ", "", x_fmt)
} else {
paste(prefix, "==", gsub("^1 \\%\\*\\% ", "", x_fmt))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment